Process output events not firing for cmd.exe from VB.NET?

28 views Asked by At

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

'''

1

There are 1 answers

1
Joel Coehoorn On

The problem is the Handles directives at the end of the method definitions. At the point where they are processed, the p object is not yet created. You'll need to use AddHandler in the button click event instead:

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
    AddHandler p.OutputDataReceived, AddressOf p_OutputDataReceived
    AddHandler p.ErrorDataReceived, AddressOf p_ErrorDataReceived

    p.Start()

End Sub