使用隐藏窗口在C#中打开一个进程

时间:2012-10-23 06:34:12

标签: c#

我有一个在本地计算机上启动进程的函数:

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。

我做错了什么?

3 个答案:

答案 0 :(得分:2)

以下程序将显示/隐藏窗口:

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

答案 1 :(得分:2)

CreateNoWindow标志仅适用于控制台进程。

详情请见此处:

其次,应用程序可以忽略WindowStyle参数 - 它在新应用程序第一次调用ShowWindow时生效,但后续调用在应用程序的控制之下。

答案 2 :(得分:1)

您需要删除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;
    }