0
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    StartInfo.FileName = "apo.exe"
    StartInfo.RedirectStandardInput = True
    StartInfo.RedirectStandardOutput = True
    StartInfo.CreateNoWindow = True
    StartInfo.UseShellExecute = False
    myprocess.StartInfo = StartInfo
    myprocess.Start()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    myprocess.StandardInput.WriteLine(txtCommand.Text)

    '------------------------------------------------------
    'If I do.close,process apo.exe will close.else ReadToEnd will hangs &can't read any string
    myprocess.StandardInput.Close()
    '------------------------------------------------------

    txtResults.Text = myprocess.StandardOutput.ReadToEnd
End Sub

there is a console program named "apo.exe",I just want to send some command to "apo.exe" and get returns. The question is when my code running at 'StandardInput.Close',apo.exe will closed.I have to send commands continuously with it running. What should I do?

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • If you don't want to close it then why are you calling `Close`? That's like saying "when I step on a landmine I get blown up so how do I stop getting blown up". `StandardInput` and `StandardOutput` are `StreamReaders` so you just write to and read from them like you would any other `StreamReaders`. Don't call `Close` until you want to close the app. – John May 02 '22 at 11:42
  • @John `StandardInput` is of course a `StreamWriter`, not a `StreamReader` :) – Jimi May 02 '22 at 12:36
  • @John Thanks for your answer.But if I don't 'close',while running to 'ReadToEnd' the app will hangs & txtResults can't read any string – caoshuaing May 02 '22 at 15:28
  • The StreamWriter should auto-flush, but you won't probably see anything if you have a debugger attached. Try to run the executable directly, see how it goes. Anyway, I suggest you use the Process' Events, which notify when some data has been written to StdOut. Always redirect StdErr, the Process may write to this stream. -- See the example here: [How do I get output from a command to appear in a control on a Form in real-time?](https://stackoverflow.com/a/51682585/7444103) (yes, it's a slightly different language) – Jimi May 02 '22 at 17:46
  • So don't call `ReadToEnd` either. If you want to write input interleaved with reading output then you obviously don't want to read to the end, because the end only occurs when the app closes. Write a line of input, read a line of output. – John May 03 '22 at 00:49

0 Answers0