I am starting a new process from my c# application.
After the process created I set its main window as a child of my app window using the ManagementEventWatcher and SetParent.
The problem is that when I write in my query WITHIN 2 every thing works fine, except that I wait to long. When I write WITHIN 1 the MainWindowHandle of the started process not created yet when the event EventArrived fired.
Is there any good way to wait for the handle to be created except using timer?
According to the MSDN documentation for Process.MainWindowHandle
you can use the Process.WaitForInputIdle()
method in order to "allow the process to finish starting, ensuring that the main window handle has been created."
Depending on how long it takes the process to finish starting you might want to wait for it in a thread, or else your UI might freeze.
Either way just go ahead and wait:
yourProcess.WaitForInputIdle();
//Do your stuff with the MainWindowHandle.
Another option would be to run your code in a thread and loop until MainWindowHandle
is not zero. To avoid getting into an infinite loop you could add some sort of timeout.
int timeout = 10000; //10 seconds.
while (yourProcess.MainWindowHandle == IntPtr.Zero && timeout > 0)
{
yourProcess.Refresh();
System.Threading.Thread.Sleep(250); //Wait 0.25 seconds.
timeout -= 250;
}
if (yourProcess.MainWindowHandle == IntPtr.Zero)
{
//Timed out, process still has no window.
return; //Do not continue execution.
}
//The rest of your code here.