Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleExecute a console program and capture its output
DescriptionThis example shows how to execute a console program and capture its output in Visual Basic 6.
Keywordsconsole program, capture output, stdout, execute
CategoriesSoftware Engineering, Windows
 
Thanks to Dipak Auddy.

Subroutine ExecAndCapture creates a pipe and executes the console application, telling it to send output and error information to the pipe. It then reads from the pipe until there's no output left to read.

 
' Call this sub to execute and capture a console app.
' Ex: Call ExecAndCapture("ping localhost", Text1)
Public Sub ExecAndCapture(ByVal sCommandLine As String, _
                          cTextBox As TextBox, _
                          Optional ByVal sStartInFolder As _
                              String = vbNullString)
Const BUFSIZE         As Long = 1024 * 10
Dim hPipeRead         As Long
Dim hPipeWrite        As Long
Dim sa                As SECURITY_ATTRIBUTES
Dim si                As STARTUPINFO
Dim pi                As PROCESS_INFORMATION
Dim baOutput(BUFSIZE) As Byte
Dim sOutput           As String
Dim lBytesRead        As Long
    
    With sa
        .nLength = Len(sa)
        .bInheritHandle = 1    ' get inheritable pipe
            ' handles
    End With 'SA
    
    If CreatePipe(hPipeRead, hPipeWrite, sa, 0) = 0 Then
        Exit Sub
    End If

    With si
        .cb = Len(si)
        .dwFlags = STARTF_USESHOWWINDOW Or _
            STARTF_USESTDHANDLES
        .wShowWindow = SW_HIDE          ' hide the window
        .hStdOutput = hPipeWrite
        .hStdError = hPipeWrite
    End With 'SI
    
    If CreateProcess(vbNullString, sCommandLine, ByVal 0&, _
        ByVal 0&, 1, 0&, ByVal 0&, sStartInFolder, si, pi) _
        Then
        Call CloseHandle(hPipeWrite)
        Call CloseHandle(pi.hThread)
        hPipeWrite = 0
        Do
            DoEvents
            If ReadFile(hPipeRead, baOutput(0), BUFSIZE, _
                lBytesRead, ByVal 0&) = 0 Then
                Exit Do
            End If
            sOutput = Left$(StrConv(baOutput(), vbUnicode), _
                lBytesRead)
            cTextBox.SelText = sOutput
        Loop
        Call CloseHandle(pi.hProcess)
    End If
    ' To make sure...
    Call CloseHandle(hPipeRead)
    Call CloseHandle(hPipeWrite)

End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated