从 CWnd::FromHandle 获得的 CWnd 的生命周期是多少?

2022-01-12 00:00:00 winapi mfc cwnd hwnd

根据 msdn,当我使用 CWnd::FromHandle 获取 CWnd*,

According to msdn, when I get a CWnd* with CWnd::FromHandle,

指针可能是临时的,不应存储以供以后使用.

The pointer may be temporary and should not be stored for later use.

我不清楚以后使用"是什么意思.它只是当前方法的范围吗?据我所知,Win32是没有GC的!

What is meant by "later use" is not clear to me. Is it only the scope of the current method? As far as I know, there is no GC in Win32!

推荐答案

MFC 维护了许多句柄映射,从 HWND 到 CWnd,从 HDC 到 CDC 等,这些句柄映射存储在线程状态中.每个句柄映射都包含一个永久映射和临时映射 - 当您调用 CWnd::Create 或 CDC::Attach 等方法时会添加永久条目,而在没有永久条目.

MFC maintains a number of handle maps, from HWND to CWnd, HDC to CDC etc, which are stored in the thread state. Each handle map contains a permanent map and temporary map - permanent entries are added when you call a method such as CWnd::Create or CDC::Attach, while temporary entries are created when you call FromHandle on a handle that doesn't have a permanent entry.

在空闲处理期间(在 CWinApp::OnIdle 中)清除临时条目,因此它们只能在处理当前消息时安全地使用.一旦您返回消息循环,或进入另一个模式循环(例如通过调用 DoModal),它们可能会被删除.

Temporary entries are cleaned up during idle processing (in CWinApp::OnIdle), so they can only safely be used while processing the current message. As soon as you return to the message loop, or enter another modal loop (e.g. by calling DoModal) then they may be deleted.

相关文章