It's quite possible using System.Diagnostics.Process.
The actual result depends on how that program actually works.
It might require some tests to get its output right.
This is a generic procedure you can use to test if your executable behaves in a standard way.
It's using tracert.exe
and ouputs its results in a RichTextBox
control.
Note that the Process.Start()
initialization uses the Process.SynchronizingObject() set to the RichTextBox
control Parent Form to avoid InvokeRequired
. But if you don't want to use a Synch object, Control.Invoke
is handled anyway, using MethodInvoker delegate.
To switch to your executable, subsitute the StartProcess()
method parameters as required.
Imports System.Diagnostics
Imports System.IO
Private CurrentProcessID As Integer = -1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
StartProcess("C:WindowsSystem32racert.exe", "stackoverflow.com")
End Sub
Private Sub StartProcess(FileName As String, Arguments As String)
Dim MyStartInfo As New ProcessStartInfo() With {
.FileName = FileName,
.Arguments = Arguments,
.WorkingDirectory = Path.GetDirectoryName(FileName),
.RedirectStandardError = True,
.RedirectStandardOutput = True,
.UseShellExecute = False,
.CreateNoWindow = True
}
Dim MyProcess As Process = New Process() With {
.StartInfo = MyStartInfo,
.EnableRaisingEvents = True,
' Setting a SynchronizingObject, we don't need to BeginInvoke.
' I leave it there anyway, in case there's no SynchronizingObject to set
' BeginInvoke can be used with or without a synchronization context.
.SynchronizingObject = Me
}
MyProcess.Start()
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
CurrentProcessID = MyProcess.Id
AddHandler MyProcess.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
If e.Data IsNot Nothing Then
BeginInvoke(New MethodInvoker(
Sub()
RichTextBox1.AppendText(e.Data + Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub))
End If
End Sub
AddHandler MyProcess.ErrorDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
If e.Data IsNot Nothing Then
BeginInvoke(New MethodInvoker(
Sub()
RichTextBox1.AppendText(e.Data + Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub))
End If
End Sub
AddHandler MyProcess.Exited,
Sub(source As Object, ev As EventArgs)
MyProcess.Close()
If MyProcess IsNot Nothing Then
MyProcess.Dispose()
End If
End Sub
End Sub
Note:
If you need to terminate more that one running processes, you'll have to modify the code a bit more.
You could use a Class object to contain the Process Id, the Process Name (eventually) and a sequential value to maintain a reference to each process run.
Use a List(Of [Class])
for this.
You might also need to modify the StartProcess()
method to pass a Control reference (the Control where the different processes output their results).
The code, as it is, needs very few modifications to achieve this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…