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

C# 控制台程序啟動外部進程並隱藏自身窗口

     編輯:關於C語言

控制台程序啟動外部進程(如記事本)後,若需隱藏自身控制台窗口,可通過 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。

同理可擴展至隱藏任意已知標題的窗口。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved