3

我正在编写一个应用程序来管理其他控制台应用程序(游戏服务器 - jampded.exe

当它在控制台中运行时,它会毫无问题地写入数据并读取命令。

在我的应用程序中,我将标准 I/O 重定向到 StreamWriter 和 StreamReader

Public out As StreamReader
Public input As StreamWriter

Dim p As New Process()
p.StartInfo.FileName = My.Application.Info.DirectoryPath & "\" &
                       TextBox6.Text 'PATH TO JAMPDED.EXE
p.StartInfo.Arguments = TextBox1.Text 'EXTRA PARAMETERS
p.StartInfo.CreateNoWindow = True 
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.UseShellExecute = False
p.Start()

input = p.StandardInput
out = p.StandardOutput

Dim thr As Thread = New Thread(AddressOf updatetextbox)
thr.IsBackground = True
thr.Start()

Sub updatetextbox()
  While True
    While Not out.EndOfStream
      RichTextBox1.AppendText(out.ReadLine())
      RichTextBox1.AppendText(vbNewLine)
    End While
  End While
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) _
                                                       Handles Button2.Click
  input.WriteLine(TextBox4.Text)
  TextBox4.Text = ""
  input.Flush()
End Sub

当我按下Button2应该从我的文本框中写入 STD/I 文本时,jampded.exe就像它没有被写入一样。输出在启动时也能很好地工作,之后当缓冲区中有大量数据时很少添加新行。

我做错了什么,还是应用程序的错?

4

1 回答 1

2

对于标准输入问题:

您确定您正在启动的应用程序正在从标准输入读取数据(而不是捕获键盘事件或其他东西)吗?要对此进行测试,请将您尝试发送到应用程序的一些文本放入一个文本文件(例如,命名为 commands.txt)。然后从命令提示符将其发送到应用程序,如下所示:

type commands.txt | jampded.exe

如果该应用程序读取这些命令,那么它确实是从标准输入读取。如果不是,那么重定向标准输入不会帮助您将数据发送到该应用程序。

对于标准输出问题:

我建议不要启动您自己的线程来处理来自其他应用程序的数据,而是执行以下操作:

AddHandler p.OutputDataReceived, AddressOf OutputData
p.Start()
p.BeginOutputReadLine()

Private Sub AddLineToTextBox(ByVal line As String)
    RichTextBox1.AppendText(e.Data)
    RichTextBox1.AppendText(vbNewLine)
End Sub
Private Delegate Sub AddLineDelegate(ByVal line As String)

Private Sub OutputData(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    If IsNothing(e.Data) Then Exit Sub
    Dim d As AddLineDelegate
    d = AddressOf AddLineToTextBox
    Invoke(d, e.Data)
End Sub

Invoke调用是必需的,因为OutputData可能会在不同的线程上调用,并且 UI 更新都必须在 UI 线程上发生。

当直接从 StandardOutput 流中读取数据时,我已经看到了同样的问题。异步读取 + 事件处理程序组合修复了它。

于 2013-10-24T02:42:27.780 回答