I am trying to open simple .net exe/notepad.exe using process.start in hidden mode. and I need the process handle later to make the application.exe to make it visible after some time.
Able to get handle only in WindowStyle.Minimized, WindowStyle.Maximized, WindowStyle.Normal. In Hidden style, it gives me 0 always.
How to get handle without using Thread.Sleep. It requires us to wait few seconds, to get handle. some exe requires more wait time, based on its performance(huge data).
public static void LaunchExe()
{
var proc = new Process
{
StartInfo =
{
FileName = "Notepad.exe", //or any simple .net exe
WindowStyle = ProcessWindowStyle.Hidden
}
};
proc.Start();
proc.WaitForInputIdle(800); //is it possible to avoid this.
Thread.Sleep(3000); //is it possible to avoid this.
Console.WriteLine("handle {0}", proc.MainWindowHandle);
//ShowWindowAsync(proc.MainWindowHandle, 1); //planned to use, to make it visible.
}
You can do something like this:
IntPtr ptr = IntPtr.Zero;
while ((ptr = proc.MainWindowHandle) == IntPtr.Zero)
{ proc.WaitForInputIdle(1 * 60000); Thread.Sleep(10); } // (1*60000 = 1min, will give up after 1min)
That way you're not wasting any more time than you need to.
You can't get the handle of a hidden process.
According to MS: A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar.
I think your only choice would be to start it normally, get the handle, then set it hidden.
This might cause some flicker, but it should work. To mitigate the flicker, you could start it minimized...