我想在 Windows 控制台中运行一个进程,之后,我想通过(通过按钮单击)一些命令并在 RichTextBox 中查看结果。
我可以启动程序并在启动后阅读响应,但是当我尝试发送任何命令时,它不起作用。我无法用这个过程“说话”……</p>
如果你有任何想法。我会欣然接受!
代码下方:
public static void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data)) {
numOutputLines++;
// Add the text to the collected output.
sortOutput.Append(Environment.NewLine + $"[{numOutputLines}] - {outLine.Data}");
//RichTextBox
MCM.ActiveForm.Invoke(MCM.AffichageTextDelegate, new object[] { outLine.Data });
}
}
public static async Task<int> RunProcessAsync() {
using (var process = new Process {
StartInfo = {
FileName = "AAA.exe",
Arguments = “-v COM74",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true
},
EnableRaisingEvents = true
})
{ return await RunProcessAsync(process).ConfigureAwait(false); }
}
private static Task<int> RunProcessAsync(Process process) {
var tcs = new TaskCompletionSource<int>();
process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
sortOutput = new StringBuilder();
process.OutputDataReceived += SortOutputHandler;
process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return tcs.Task;
}
private async void Btn_Click(object sender, EventArgs e) {
await RunProcessAsync();
}