萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 啟動外部程式並等待就緒:Process.Start 完整實戰範例

需求場景

啟動外部應用程式 (test.exe) 並傳遞參數 (abc.prj),偵測視窗句柄確認主視窗已建立,避免過早操作導致失敗。

完整代碼 (WinForms 事件處理器)


using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

public partial class MainForm : Form
{
    [DllImport("user32.dll", SetLastError = true)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    private void btnCreate_Click(object sender, EventArgs e)
    {
        // 1. 檢查是否已執行 (避免重複啟動)
        int hWnd = FindWindow(null, "test"); // 視窗標題
        if (hWnd > 0)
        {
            MessageBox.Show($"程式已執行中,視窗句柄: {hWnd}");
            return;
        }

        try
        {
            var proc = new Process();
            proc.StartInfo.FileName = @"C:\test.exe";      // 可執行檔路徑
            proc.StartInfo.Arguments = @"C:\Temp\abc.prj"; // 命令列參數
            proc.StartInfo.UseShellExecute = true;         // 使用 Shell 執行 (支援關聯程式)
            proc.Start();

            // 2. 等待輸入閒置 (UI 執行緒進入訊息迴圈)
            proc.WaitForInputIdle(10000); // 最多等 10 秒

            // 3. 輪詢主視窗句柄 (WaitForInputIdle 不保證主視窗已建立)
            for (int i = 0; i < 100; i++)
            {
                hWnd = FindWindow(null, "PowerReuse (Beta)"); // 實際視窗標題
                if (hWnd > 0) break;
                Thread.Sleep(100);
            }

            if (hWnd == 0)
            {
                MessageBox.Show("找不到目標視窗句柄,啟動可能失敗。");
            }
            else
            {
                MessageBox.Show($"啟動成功!句柄: {hWnd}, Process.Handle: {proc.MainWindowHandle}, 標題: {proc.MainWindowTitle}");
                // 後續可用 hWnd 進行 SendMessage/PostMessage 互動
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("啟動失敗: " + ex.Message);
        }
    }
}

關鍵 API 說明

API用途注意事項
Process.Start()啟動進程UseShellExecute=true 可啟動關聯程式 (如 .pdf、.url),但無法重導向 I/O
WaitForInputIdle(ms)等待進程進入訊息迴圈僅適用 GUI 應用;主控台程式立即返回
Process.MainWindowHandle取得主視窗句柄可能為 IntPtr.Zero (視窗未建立或非 GUI)
FindWindow(lpClassName, lpWindowName)依類別/標題尋找頂層視窗標題需完全匹配;類別名可用 Spy++ 取得
Thread.Sleep(ms)輪詢間隔避免忙碌等待佔 CPU

常見坑與解法

  • 路徑含空白:@"""C:\Program Files\App\app.exe"""" 或 StartInfo.Arguments 獨立設定。
  • 管理員權限:目標程式需提權時,StartInfo.Verb = "runas" (需 UseShellExecute=true)。
  • 64/32 位元:FindWindow 簽章需 SetLastError=true,IntPtr 對應 64-bit。
  • 多視窗應用:FindWindow 只找第一個;改用 EnumWindows + 過濾 GetWindowThreadProcessId 精確匹配進程 ID。

現代替代:ProcessStartInfo 進階用法


var psi = new ProcessStartInfo {
    FileName = "dotnet",
    Arguments = "run --project MyApp.csproj",
    WorkingDirectory = @"C:\Projects\MyApp",
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false, // 必須 false 才能重導向
    CreateNoWindow = true    // 無視窗模式
};
var proc = Process.Start(psi);
string output = await proc.StandardOutput.ReadToEndAsync();
await proc.WaitForExitAsync();

總結

C# 啟動外部程式核心是 Process.Start,但「啟動成功」≠「視窗就緒」。組合 WaitForInputIdle + FindWindow 輪詢是經典可靠模式。現代 .NET Core/.NET 5+ 建議使用 WaitForExitAsync、RedirectStandardOutput 等非同步 API,避免阻塞 UI 執行緒。

copyright © 萬盛學電腦網 all rights reserved