Just like the comments suggest a combination of static
member functions and SetWindowLongPtr
can be used to achieve what you are looking to do.
Here is a sample class declaration that defines the static WindowProc
as a member function.
class MyClass
{
public:
void MainThreadProc ();
private:
static LRESULT CALLBACK WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT _WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
};
The MainThreadProc method will create the window. Make sure to pass in this
to CreateWindowEx
as that is how you will get access to your class members.
void MyClass::MainThreadProc()
{
MSG msg;
HINSTANCE hinstance = GetModuleHandle (NULL);
WNDCLASSEX wcx = {0};
HWND hwnd = NULL;
wcx.cbSize = sizeof wcx;
wcx.hInstance = hinstance;
wcx.hCursor = LoadCursor (NULL, IDC_NO);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcx.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wcx.lpfnWndProc = WindowProc;
wcx.lpszClassName = L"MyWindowClass";
RegisterClassEx (&wcx);
hwnd = CreateWindowEx ( WS_EX_APPWINDOW,
L"MyWindowClass",
L"MyWindow",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hinstance,
this);
ShowWindow (hwnd, SW_SHOWDEFAULT);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
In WindowProc
you will store the this
object using SetWindowLongPtr
for future use.
LRESULT MyClass::WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (WM_NCCREATE == uMsg)
{
SetWindowLongPtr (hwnd, GWLP_USERDATA, (LONG_PTR) ((CREATESTRUCT*) lParam)->lpCreateParams);
return TRUE;
}
return ((MyClass*) GetWindowLongPtr (hwnd, GWLP_USERDATA))->_WindowProc (hwnd, uMsg, wParam, lParam);
}
And for completeness sake, here is the final member function for processing window messages and you will have access to all class members at this point.
LRESULT MyClass::_WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage (S_OK);
break;
default:
return DefWindowProc (hwnd, uMsg, wParam, lParam);
}
return 0;
}
HWND
handle - see e.g.SetProp
orSetWindowLongPtr
static
member functions can be used as callback functions without too much effort. Makingnon-static
member function work as callback functions requires creating wrapper functions.