Handling invalid window handle

Luca picture Luca · Aug 2, 2010 · Viewed 8.3k times · Source

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.

Answer

Chris Becke picture Chris Becke · Aug 2, 2010

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.