views:

112

answers:

4

The application retrieve window handles, using Enum* routines.

It happens that in the while the application manage the handle (get class name, window statistics...) of an enumerated/created window, the handle is no more valid. The code managing window handles are protected using a try/catch block, but the window handle is stored and the successively used for managing the represented window.

How to handle the window handle lifetime? It is possible to detect the handle invalidity?

I'd like to avoid try/catch blocks every time the application uses the window handles.

+1  A: 

You can use the GetWindowInfo function. It returns 0 if the handle is not valid.

onof
+1  A: 

You can pass it to IsWindow() to validate it.
There are a couple of caveats, however both will apply to pretty much any approach to this:

A thread should not use IsWindow for a window that it did not create because the window could be destroyed after this function was called. Further, because window handles are recycled the handle could even point to a different window.

If your doing this to a window in one of your own external apps, you could add a 2nd tier of validation by Set/GetProp()'ing a unique identifier of some kind.

Alex K.
+1  A: 

Window handles are only safe if used from the thread that created the window. From any other thread, all you can know about a window handle is, it was valid sometime in the past. right now, it may or may not be, and if it is, it could refer to a different window than intended entirely.

Chris Becke
A: 

I already have the actual solution... but I didn't know about this until now!

Thank you all for having clarified about the window handle lifetime, but there is actually a method for being detected about window handle lifetime: CbtProc.

In the case the hook is installed system wide, it's possible to notify specific applications (it depends all on real implementation of the CBT hook) about a window destroy, which indicates that the a specific handle won't be valid after the notification.

From the documentation:

HCBT_DESTROYWND Specifies the handle to the window about to be destroyed.

Of course the access of the handles using WINAPI routines must be synchronized with the notification system, which doesn't seem to give good feasibility (CBT hook actually blocks window destroy because it is synchronized with the application logic).

Luca