I'm trying to kind of virtualize a command window, so that I can run terminal commands programatically. I need it to be persistent, since I'll be running commands that depend on the previous command (such as changing directories).
But I'm failing in the first place to receive output from the command window. Even though I am enabling events and redirecting the output, I don't seem to be able to get my events below to fire.
What is the correct way to control input and trap output from a command window, programmatically, in VB.NET?
Thanks!
'''
Dim WithEvents p As Process
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
p = New Process
p.StartInfo = New ProcessStartInfo("cmd.exe")
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = False
p.EnableRaisingEvents = True
p.Start()
End Sub
Private Sub p_OutputDataReceived(sender As Object, e As DataReceivedEventArgs) Handles p.OutputDataReceived
Debug.Print("data: " + e.Data)
End Sub
Private Sub p_ErrorDataReceived(sender As Object, e As DataReceivedEventArgs) Handles p.ErrorDataReceived
Debug.Print("data: " + e.Data)
End Sub
'''
The problem is the
Handlesdirectives at the end of the method definitions. At the point where they are processed, thepobject is not yet created. You'll need to useAddHandlerin the button click event instead: