從外部應用程式擷取 Windows 窗體文字方塊中的控制台輸出
本指南示範如何使用 .NET 的進程管理功能將單獨程式的控制台輸出重新導向到 Windows 表單應用程式中的文字方塊。
實作步驟:
Process
物件來表示外部控制台應用程式。 StartInfo
屬性以指定外部程式的路徑(FileName
)、停用shell 執行(UseShellExecute = false
) 以及啟用標準輸出和錯誤重定向(RedirectStandardOutput = true
, RedirectStandardError = true
)。 另外,啟用事件引發 (EnableRaisingEvents = true
)。 OutputDataReceived
事件。此事件處理程序將接收重定向的輸出流。 這是一個說明此過程的 C# 範例:
<code class="language-csharp">void Method() { var process = new Process(); process.StartInfo.FileName = @"C:\ConsoleApp.exe"; // Replace with your console app's path process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.EnableRaisingEvents = true; process.OutputDataReceived += Process_OutputDataReceived; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); } private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { // Update the TextBox with the received data (e.Data) on the UI thread. if (e.Data != null) { this.BeginInvoke((MethodInvoker)delegate { this.textBox1.AppendText(e.Data + Environment.NewLine); // Assuming your TextBox is named textBox1 }); } }</code>
請記得將 "C:ConsoleApp.exe"
替換為外部控制台應用程式的實際路徑。 BeginInvoke
方法確保 TextBox 在 UI 執行緒上安全更新,防止跨執行緒異常。
以上是如何將控制台輸出重新導向到 Windows 窗體文字方塊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!