首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 重導向 Windows 主控台程式輸出至 WinForm 介面

     編輯:關於C#

需在 WinForm 應用程式中啟動主控台程式(如 ipconfig、ping、Oracle exp 等),並即時將其標準輸出顯示於介面上。本文提供完整範例,使用 Process.StartInfo.RedirectStandardOutput 捕獲輸出流,搭配委派跨執行緒更新 UI。

核心步驟

  1. 建立 Process,設定 RedirectStandardOutput = true、UseShellExecute = false、CreateNoWindow = true。
  2. 啟動程序,取得 StandardOutput 串流(StreamReader)。
  3. 迴圈逐行讀取,透過委派 Invoke 更新 UI 控制項(如 TextBox)。
  4. WaitForExit() 等待結束。

完整程式碼

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace WindowsApplication8
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        // 委派定義:用於跨執行緒更新 UI
        delegate void DReadLine(string line);

        private void ExecuteCommand(string fileName, string args, DReadLine onReadLine)
        {
            var p = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = args,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };

            p.Start();
            using (StreamReader reader = p.StandardOutput)
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    onReadLine(line); // 透過委派更新 UI
                }
            }
            p.WaitForExit();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            ExecuteCommand("ipconfig", "", PrintMessage);
        }

        private void PrintMessage(string line)
        {
            if (textBox1.InvokeRequired)
                textBox1.Invoke(new DReadLine(PrintMessage), line);
            else
                textBox1.AppendText(line + Environment.NewLine);
        }
    }
}

關鍵細節說明

設定用途
UseShellExecute = false必須為 false 才能重導向輸出
CreateNoWindow = true不顯示黑色主控台視窗
RedirectStandardOutput啟用標準輸出重導向
StreamReader.ReadLine()逐行讀取,適合即時顯示
InvokeRequired/Invoke確保 UI 更新在主執行緒進行

進階應用建議

  • 同時捕獲錯誤輸出:另設 RedirectStandardError = true,讀取 p.StandardError。
  • 非同步讀取:使用 p.OutputDataReceived 事件搭配 p.BeginOutputReadLine(),避免阻塞 UI 執行緒。
  • 互動式程式:若需輸入指令,設定 RedirectStandardInput = true,寫入 p.StandardInput。
  • 編碼問題:主控台程式輸出編碼可能非 UTF-8,建議指定 StandardOutput.CurrentEncoding 或使用 Encoding.GetEncoding(950)(繁體中文 Big5)。

常見坑點

  • 忘記 UseShellExecute = false → 重導向失效。
  • 同步 ReadLine() 迴圈阻塞 UI → 改用非同步事件或 `Task.Run` 包裝。
  • 程式大量輸出導致 TextBox 卡頓 → 定期清理或使用虛擬化列表。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved