I needed to do some cmd stuff today and found this thread
useful. I ended up embedding the example in this post into a class which makes it easy to use. At least I think so...
Code:
Class CMDThread
Public Param As String
Public isFinished As Boolean = False
Private tr As Thread = Nothing
Private results As String = ""
Private myprocess As New Process
Private StartInfo As New System.Diagnostics.ProcessStartInfo
Public Function Start() As Thread
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False 'required to redirect
StartInfo.CreateNoWindow = True 'creates no cmd window
myprocess.StartInfo = StartInfo
myprocess.Start()
tr = New Thread(AddressOf Me.work)
tr.Start()
Return tr
End Function
Public Sub Join()
tr.Join()
End Sub
Public Function GetOutput() As String
GetOutput = results
results = "" 'Not sure if this is safe while thread is executing... seem to work
End Function
Private Sub work()
myprocess.StandardInput.WriteLine(Param & vbCrLf & "exit") 'the command you wish to run, with an exit at the end to terminate process after run
While myprocess.StandardOutput.EndOfStream = False
results += myprocess.StandardOutput.ReadLine() & vbCrLf
End While
isFinished = True
End Sub
End Class
To launch a couple of threads and use join to wait for the last one:
Code:
Dim threadA, threadB As New CMDThread
Dim res As String = ""
threadA.Param = "ping -n 2 127.0.0.1"
threadB.Param = "tracert -h 10 -d -w 30 vbforums.com"
threadA.Start()
threadB.Start()
While Not threadA.isFinished
res = threadA.GetOutput
...do stuff...
End While
'A is finished
If Not threadB.isFinished Then
threadB.Join() 'wait until B is finished
End If
res = threadB.GetOutput
Cheers!