Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c++ - Best method for storing this pointer for use in 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();
}

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.

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.

Edit: 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.

Edit: ATL uses a thunk for accessing the this pointer. MFC uses a hashtable lookup of HWNDs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your constructor, call CreateWindowEx with "this" as the lpParam argument.

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

Which allows you to do this:

wndptr->DoSomething();

Of course, you could use the same technique to call something like your function above:

wndptr->WndProc(msg, wparam, lparam);

... which can then use its "this" pointer as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...