我很想知道存储 this
指针以在 WndProc
中使用的最佳/常用方法.我知道几种方法,但据我所知,每种方法都有自己的缺点.我的问题是:
I'm interested to know the best / common way of storing a this
pointer for use in the WndProc
. I know of several approaches, but each as I understand it have their own drawbacks. My questions are:
生成这种代码有哪些不同的方法:
What different ways are there of producing this kind of code:
CWindow::WndProc(UINT msg, WPARAM wParam, LPARAM)
{
this->DoSomething();
}
我可以想到 Thunks、HashMaps、线程本地存储和窗口用户数据结构.
I can think of Thunks, HashMaps, Thread Local Storage and the Window User Data struct.
每种方法的优缺点是什么?
What are the pros / cons of each of these approaches?
获得代码示例和建议的积分.
Points awarded for code examples and recommendations.
这纯粹是为了好奇.使用 MFC 后,我一直想知道它是如何工作的,然后开始考虑 ATL 等.
This is purely for curiosities sake. After using MFC I've just been wondering how that works and then got to thinking about ATL etc.
我可以在窗口 proc 中有效使用 HWND
的最早位置是什么?它被记录为 WM_NCCREATE
- 但如果您实际进行实验,那不是发送到窗口的第一条消息.
What is the earliest place I can validly use the HWND
in the window proc? It is documented as WM_NCCREATE
- but if you actually experiment, that's not the first message to be sent to a window.
ATL 使用 thunk 来访问 this 指针.MFC 使用 HWND
的哈希表查找.
ATL uses a thunk for accessing the this pointer. MFC uses a hashtable lookup of HWND
s.
在您的构造函数中,使用this"作为 lpParam 参数调用 CreateWindowEx.
In your constructor, call CreateWindowEx with "this" as the lpParam argument.
然后,在 WM_NCCREATE 上,调用以下代码:
Then, on WM_NCCREATE, call the following code:
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT*)lParam)->lpCreateParams);
SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
然后,在窗口过程的顶部,您可以执行以下操作:
Then, at the top of your window procedure you could do the following:
MyWindowClass *wndptr = (MyWindowClass*) GetWindowLongPtr(hwnd, GWL_USERDATA);
允许您这样做:
wndptr->DoSomething();
当然,您可以使用相同的技术来调用上面的函数:
Of course, you could use the same technique to call something like your function above:
wndptr->WndProc(msg, wparam, lparam);
... 然后可以按预期使用其this"指针.
... which can then use its "this" pointer as expected.
这篇关于存储此指针以在 WndProc 中使用的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!