控制台程序啟動外部進程(如記事本)後,若需隱藏自身控制台窗口,可通過 P/Invoke 調用 Windows API FindWindow、ShowWindow 實現。
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
class TestClass
{
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "ShowWindow")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main(string[] args)
{
new TestClass();
}
public TestClass()
{
// 啟動記事本
Process p = new Process();
p.StartInfo.FileName = "NOTEPAD.EXE";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.Close();
// 隱藏自身控制台
Console.Title = "1111"; // 設定唯一標題以便查找
IntPtr hWnd = FindWindow(null, "1111");
if (hWnd != IntPtr.Zero)
ShowWindow(hWnd, 0); // SW_HIDE = 0
else
Console.WriteLine("error");
Console.Read(); // 防止主線程結束
}
}
CreateNoWindow = true 僅對啟動的進程生效,不影響當前控制台。Console.Title,以便 FindWindow 精確定位。ShowWindow(hWnd, 0) 隱藏窗口;若需最小化用 6,正常顯示用 1。同理可擴展至隱藏任意已知標題的窗口。