問題描述
我很想知道存儲 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模板網!