How to hide / show process in C #?

I am trying to start an external process in a Visual C # 2010 application - Windows Forms. The goal is to start the process as a hidden window and display the window later.

I updated my progress:

//Initialization
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hwnd, bool enable);
[DllImport("user32.dll")]
private static extern bool MoveWindow(IntPtr handle, int x, int y, int width, 
int height, bool redraw);

SW_SHOW = 5;

In my main function, the following was installed:

ProcessStartInfo info = new ProcessStartInfo("process.exe");
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = Process.Start(info);

p.WaitForInputIdle();
IntPtr HWND = p.MainWindowHandle;

System.Threading.Thread.Sleep(1000);    

ShowWindow(HWND, SW_SHOW);
EnableWindow(HWND, true);
MoveWindow(HWND, 0, 0, 640, 480, true);

However, since the window was started as "hidden" p.MainWindowHandle = 0. I can not successfully show the window. I also tried HWND = p.Handlewithout success.

Is there a way to provide a new handle to my window? This could potentially solve my problem.

Literature:

MSDN ShowWindow

MSDN Forums

How to import .dll

+5
source share
3 answers

Finally, the process is working correctly. Thanks to all your help, I came up with this fix.

p.MainWindowHandle 0, user32 FindWindow(), .

//Initialization
int SW_SHOW = 5;

[DllImport("user32.dll",SetLastError=true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, WindowShowStyle nCmdShow);

[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hwnd, bool enabled);

:

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "notepad";
info.UseShellExecute = true;
info.WindowStyle = ProcessWindowStyle.Hidden;

Process p = Process.Start(info);
p.WaitForInputIdle();
IntPtr HWND = FindWindow(null, "Untitled - Notepad");

System.Threading.Thread.Sleep(1000);

ShowWindow(HWND, SW_SHOW);
EnableWindow(HWND, true);

:

pinvoke.net: FindWindow()

+10

:

int hWnd;
Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
    if (pr.ProcessName == "notepad")
    {
        hWnd = pr.MainWindowHandle.ToInt32();
        ShowWindow(hWnd, SW_HIDE);
    }
}
+2

The document states that for use ProcessWindowStyle.Hiddenyou must also set ProcessStartInfo.UseShellExecuteto false. http://msdn.microsoft.com/en-us/library/system.diagnostics.processwindowstyle.aspx

You need to somehow recognize the window handle in order to display it later.

+1
source

All Articles