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

C# 主控台應用程式隱藏自身視窗並啟動新程式技巧

     編輯:關於C#

需求情境

主控台程式啟動後立即隱藏自己的視窗,並在背景啟動另一個程式 (GUI 或 CLI),不讓使用者看到黑色視窗閃爍。

核心技術:P/Invoke Win32 API


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(); // 保持執行以便觀察
    }
}

替代方案比較

進階:編譯期直接產生無主控台執行檔


// .csproj

  WinExe  

或命令列編譯:`csc /target:winexe Program.cs`

總結

若**已有主控台專案**需快速隱藏視窗:`FindWindow` + `ShowWindow(SW_HIDE)` 最直接。
若**新專案**不需要主控台輸出:專案屬性 **Output Type = Windows Application** (`WinExe`) 最乾淨、零程式碼、零閃爍。
若需**動態切換**:`FreeConsole`/`AttachConsole`/`AllocConsole` 組合使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方案優點缺點適用場景
P/Invoke ShowWindow即時隱藏已顯示視窗視窗會短暫閃現、需 P/Invoke現有主控台專案快速修改
專案屬性 → Output Type: Windows Application完全無主控台視窗、無需程式碼`Console.WriteLine` 無輸出、無法附加主控台純 GUI/背景服務、不需主控台輸出
編譯器選項 `/subsystem:windows`同 Windows Application同上同上
啟動時 `ProcessStartInfo.CreateNoWindow=true` (啟動子程式)子程式無視窗不影響父主控台視窗啟動 CLI 工具隱藏
FreeConsole() + AttachConsole()動態分離/附加主控台較複雜需條件性顯示主控台