Handling invalid window handle

泪湿孤枕 提交于 2019-12-12 20:26:00

问题


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:


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.




回答2:


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).




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/3386845/handling-invalid-window-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!