' 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
|