我正在编写一个应用程序来管理其他控制台应用程序(游戏服务器-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
当我按应该从我的文本框中写入STD / I文本的
Button2
时,jampded.exe
的行为就像未写入一样。另外,Output在启动时效果很好,在缓冲区中有大量数据的情况下,很少添加新行。我是在做错什么,还是应用程序的错误?
最佳答案
对于标准输入问题:
您确定要启动的应用程序正在从标准输入读取数据(而不是捕获键盘事件或其他事件)吗?要对此进行测试,请将您要发送给应用程序的一些文本放在一个文本文件中(例如,命名为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流中读取数据时,我看到了批量数据出现相同的问题。异步读取+事件处理程序组合修复了它。