简体   繁体   中英

How to start a process and set its main window as a child window of my app

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM