Dina
Dina

Reputation: 1406

Opening a process in C# with hidden window

I have a function for starting processes on a local machine:

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;
}

It is supposed to start the process without opening a new window. Indeed, when I test it with timeout.exe no console window is opened. But when I test it with notepad.exe or calc.exe their windows still open.

I saw online that this method works for other people. I'm using .NET 4.0 on Windows 7 x64.

What am I doing wrong?

Upvotes: 3

Views: 10860

Answers (3)

Ben
Ben

Reputation: 35663

The CreateNoWindow flag applies to Console processes only.

See here for the details:

Secondly applications can ignore the WindowStyle argument - it has effect the first time the new application calls ShowWindow, but subsequent calls are under the control of the application.

Upvotes: 3

Azodious
Azodious

Reputation: 13882

Following program will show/hide the window:

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
        }
    }
}

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

Upvotes: 2

Amirshk
Amirshk

Reputation: 8258

You need to remove the 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;
    }

Upvotes: 1

Related Questions