I am attempting to learn about creating windows in c++, I have looked at an article about creating a wrapper class but I don’t really understand it. So far I know that you can’t have a class method WndProc (I dont know why) but honestly, that is all. Can somebody give an explanation, also explaining the reinterpret_cast? Here is the article.
LRESULT CALLBACK Window::MsgRouter(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
Window *wnd = 0;
if(message == WM_NCCREATE)
{
// retrieve Window instance from window creation data and associate
wnd = reinterpret_cast<Window *>((LPCREATESTRUCT)lparam)->lpCreateParams;
::SetWindowLong(hwnd, GWL_USERDATA, reinterpret_cast<long>(wnd));
// save window handle
wnd->SetHWND(hwnd);
}
else
// retrieve associated Window instance
wnd = reinterpret_cast<Window *>(::GetWindowLong(hwnd, GWL_USERDATA));
// call the windows message handler
wnd->WndProc(message, wparam, lparam);
}
Thanks in advance, ell.
The
MsgRouter()procedure acts as a proxy between the Windows message handling system to theWindowinstance associated with aHWND. It routes Windows messages to C++ objects.A pointer to the
Windowinstance is passed to theMsgRouter()procedure via the last parameter of theCreateWindow()function. When you first create aHWNDviaCreateWindow()(orCreateWindowEx()), some messages are sent – one of them beingWM_NCCREATE. When the procedure receives aWM_NCCREATEmessage, theLPARAMparameter contains a pointer to aCREATESTRUCTwhich contains the arguments that was passed into theCreateWindow()function. The procedure retrieves theWindowinstance pointer from theCREATESTRUCTand saves it in theHWNDby setting it as an attribute of theHWND(GWL_USERDATAviaSetWindowLong()).Now that the pointer has been saved, the window procedure can from now on retrieve a pointer to the original
Windowinstance from aHWNDviaGetWindowLong()when it receives a message. Finally, the window procedure callsWndProc()on the retrievedWindowpointer, passing in the exact message and parameters, so theWindowinstance can handle the message.