tags:

views:

416

answers:

2

I am trying to find the handle to a dialog as soon as it opens.

Now as soon as dialog is opened I try to call FindWindowEx for that dialog in a separate thread but it returns NULL.

I then put some sleep before calling FindWindowEx. It works some time after putting sleep.

It looks like FindWindowEx is getting called before even dialog is created and sleep is helping to create the dialog and hence some times it work.

Now I have put some random value in sleep. And it doesnot look a good approach since it can fail anytime.

Is there any full proof approach so that I may get handle every time via FindWindowEx without making thread to sleep.

A: 

A very straightforward solution would be to call FindWindowEx repeatedly in a loop.

HWND h = NULL;
while (1) {
      h = FindWindowEx(...);
      if (h) {
         break;
      } 
      Sleep(100);
   }

That's not bullet-proof - it's an infinite loop if the dialog nevers opens, or is closed too quickly (although that's unlikely). To catch both cases, let the main thread (which creates and runs the dialog) maintain a simple bool property that the worker thread queries to find out whether there's still a dialog around.

Alexander Gessler
It would be very nice if the downvotwer told me *why* he considered this a bad answer. It is simple and solves the problem without hooking ('course, OP says he doesn't want to sleep, but I assume he means the single, random sleep call he mentions).
Alexander Gessler
+1  A: 

If the dialog you are looking for is your dialog -- that is, you control the code -- then you can send a message from your dialog to your watching app that says, "Oh, hi there!"

If the dialog is not yours, and you don't want to spin, you can create a Windows hook on the WM_CREATE message.

John Dibling