簡體   English   中英

使用隱藏窗口在C#中打開一個進程

[英]Opening a process in C# with hidden window

我有一個在本地計算機上啟動進程的函數:

public int StartProcess(string processName, string commandLineArgs = null)
{
    Process process = new Process();
    process.StartInfo.FileName = processName;
    process.StartInfo.Arguments = commandLineArgs;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.ErrorDialog = false;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.Start();
    return process.Id;
}

它應該在不打開新窗口的情況下啟動該過程。 實際上,當我使用timeout.exe測試它時,沒有打開控制台窗口。 但是當我使用notepad.exe或calc.exe測試它們時,它們的窗口仍然打開。

我在網上看到這種方法適用於其他人。 我在Windows 7 x64上使用.NET 4.0。

我究竟做錯了什么?

CreateNoWindow標志僅適用於控制台進程。

有關詳情,請參閱此處:

其次,應用程序可以忽略WindowStyle參數 - 它在新應用程序第一次調用ShowWindow時生效,但后續調用在應用程序的控制之下。

以下程序將顯示/隱藏窗口:

using System.Runtime.InteropServices;
class Program
{
    [DllImport("user32.dll")]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SW_HIDE = 0;
    const int SW_SHOW = 5;

    static void Main()
    {
        // The 2nd argument should be the title of window you want to hide.
        IntPtr hWnd = FindWindow(null, "Untitled - Notepad");
        if (hWnd != IntPtr.Zero)
        {
            //ShowWindow(hWnd, SW_SHOW);
            ShowWindow(hWnd, SW_HIDE); // Hide the window
        }
    }
}

資料來源: http//social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/1bc7dee4-bf1a-4c41-802e-b25941e50fd9

您需要刪除process.StartInfo.UseShellExecute = false

    public int StartProcess(string processName, string commandLineArgs = null)
    {
        Process process = new Process();
        process.StartInfo.FileName = processName;
        process.StartInfo.Arguments = commandLineArgs;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.ErrorDialog = false;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        return process.Id;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM