我正在执行一个exe文件,其中包含来自我的c#winform的一些c代码,但只有在完成exe的执行后才能获得c代码的完整输出。我希望exe将它的输出同步传递给我的winform(实时逐行)。
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "background.exe",
Arguments = command,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
ConsoleWindow.AppendText(proc.StandardOutput.ReadLine());
ConsoleWindow.AppendText(Environment.NewLine);
}
答案 0 :(得分:0)
试试这个,它是this example:
的松散改编 private void button1_Click(object sender, EventArgs e)
{
var consoleProcess = new Process
{
StartInfo =
{
FileName =
@"background.exe",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
consoleProcess.OutputDataReceived += ConsoleOutputHandler;
consoleProcess.StartInfo.RedirectStandardInput = true;
consoleProcess.Start();
consoleProcess.BeginOutputReadLine();
}
private void ConsoleOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
// This is the method in your form that's
// going to display the line of output from the console.
WriteToOutput(outLine.Data);
}
请注意,从控制台接收输出的事件处理程序正在另一个线程上执行,因此您必须确保在UI线程上发生用于在表单上显示输出的任何内容。