c# MainWindowHandle always zero

2019-05-29 03:58发布

I read a few threads about the MainWindowHandle but i couldnt find a solution for my problem, i'm starting a gui application and want to get the MainWindowHandle through the process object, but the handle value is always zero if i'm not going to wait with thread.sleep() until the gui is loaded. i'm also tried to use WaitForInputIdle but it didnt help at all.

process.Start();

process.WaitForInputIdle(1000);
while (process.MainWindowHandle == IntPtr.Zero)
{
     Thread.Sleep(100);
}
// do something with the handle

he is never leaving the while, if i'm replacing the waitforinputidle with a normal thread.sleep he gets the handle right.

to put it in simply words: i only want to continue with my code if i get a handle != zero but i dont want to wait a static time for this

1条回答
Melony?
2楼-- · 2019-05-29 04:48

The value stored in MainWindowHandle is cached. Add a process.Refresh() within your loop to invalidate that value:

while (process.MainWindowHandle == IntPtr.Zero)
{
    Thread.Sleep(100);
    process.Refresh();
}
查看更多
登录 后发表回答