Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# MainWindowHandle always zero

Tags:

c#

process

handle

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

like image 277
dontcare Avatar asked Nov 19 '25 03:11

dontcare


1 Answers

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();
}
like image 108
Tung Avatar answered Nov 21 '25 19:11

Tung