I am attempting to start an external process in a Visual C# 2010 - Windows Forms application. The goal is to start the process as a hidden window, and unhide the window at
Finally, the process is operating properly. Thanks to all of your help, I came up with this fix.
The p.MainWindowHandle was 0, so I had to use the user32 FindWindow() function to get the window handle.
//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, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hwnd, bool enabled);
And in my main function:
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);
References:
pinvoke.net: FindWindow()
Edit: Removed WindowShowStyle from the dllImport declaration: you can define this as an int instead. I defined an enum called WindowShowStyle to define the constants outlined in this article. It just better fits my coding patterns to have enums defined instead of using constant or hard-coded values.
Sample code to unhide the window:
int hWnd;
Process[] processRunning = Process.GetProcesses();
foreach (Process pr in processRunning)
{
if (pr.ProcessName == "notepad")
{
hWnd = pr.MainWindowHandle.ToInt32();
ShowWindow(hWnd, SW_HIDE);
}
}
The documention details that to use ProcessWindowStyle.Hidden
you must also set ProcessStartInfo.UseShellExecute
to false. http://msdn.microsoft.com/en-us/library/system.diagnostics.processwindowstyle.aspx
You would have to somehow know the window handle to unhide it later.