主控台程式啟動後立即隱藏自己的視窗,並在背景啟動另一個程式 (GUI 或 CLI),不讓使用者看到黑色視窗閃爍。
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program
{
// Win32 API 宣告
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_HIDE = 0;
private const int SW_SHOW = 5;
static void Main()
{
// 1. 設定唯一標題方便尋找
Console.Title = "MyHiddenConsole_" + Guid.NewGuid().ToString("N");
// 2. 啟動目標程式 (不等待)
var psi = new ProcessStartInfo
{
FileName = "notepad.exe",
UseShellExecute = true
};
Process.Start(psi);
// 3. 尋找並隱藏自己的主控台視窗
IntPtr hWnd = IntPtr.Zero;
for (int i = 0; i < 10; i++) // 重試幾次,等待視窗建立
{
hWnd = FindWindow(null, Console.Title);
if (hWnd != IntPtr.Zero) break;
System.Threading.Thread.Sleep(50);
}
if (hWnd != IntPtr.Zero)
ShowWindow(hWnd, SW_HIDE);
else
Console.Error.WriteLine("找不到自身視窗");
// 4. 主程式可繼續背景工作,或直接結束
// Environment.Exit(0); // 立即結束
Console.ReadLine(); // 保持執行以便觀察
}
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| P/Invoke ShowWindow | 即時隱藏已顯示視窗 | 視窗會短暫閃現、需 P/Invoke | 現有主控台專案快速修改 |
| 專案屬性 → Output Type: Windows Application | 完全無主控台視窗、無需程式碼 | `Console.WriteLine` 無輸出、無法附加主控台 | 純 GUI/背景服務、不需主控台輸出 |
| 編譯器選項 `/subsystem:windows` | 同 Windows Application | 同上 | 同上 |
| 啟動時 `ProcessStartInfo.CreateNoWindow=true` (啟動子程式) | 子程式無視窗 | 不影響父主控台視窗 | 啟動 CLI 工具隱藏 |
| FreeConsole() + AttachConsole() | 動態分離/附加主控台 | 較複雜 | 需條件性顯示主控台 |