[英]Synchronously reading stdout of a process
我正在執行一個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);
}
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線程上進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.