Maybe this is just a code organization issue, maybe there is some extremely fundamental C++ knowledge that I am lacking -- I have tried for hours to arrive at a reasonable solution, and nothing appears to work, so I am turning to the internet.
I am writing a Direct2D application for game development, and I am trying to get mouse coordinates from the WndProc lParam when there is a WM_MOUSEMOVE message, as is outlined and recommended in the MSDN article here. Here is how the relevant portions of the project are configured.
window.h
struct Window {
HWND _hwnd;
bool Initialize(int width, int height);
void RunMessageLoop();
};
window.cpp
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_MOUSEMOVE:
int xPosAbsolute = GET_X_PARAM(lParam); // as is suggested by MSDN
int yPosAbsolute = GET_Y_PARAM(lParam); // as is suggested by MSDN
...
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
bool Window::Initialize(int width, int height) {
WNDCLASS wc;
wc.lpfnWndProc = WndProc;
// etc...
}
void Window::RunMessageLoop() {
MSG Msg;
while (true)
{
GetMessage(&Msg, NULL, 0, 0);
TranslateMessage(&Msg);
DispatchMessage(&Msg);
};
}
main.cpp
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
{
// ...
while (true) {
int absolute_mouse_pos_x = ???;
int absolute_mouse_pos_y = ???;
// etc...
}
return 0;
}
My question: How can I reasonably assign (and update) absolute_mouse_pos_x and absolute_mouse_pos_y in main.cpp with the xPosAbsolute/yPosAbsolute values from the WndProc function in window.cpp?
The first thing that came to mind was instancing the WndProc function so that it has access to the members of the Window struct, but this is impossible/impractical due to the signature of a member function having a hidden "this" parameter, as other answers on Stack Overflow such as this one have detailed.
After that, I tried creating global variables in window.h, assigning them in the WndProc function in window.cpp, and referencing them in main.cpp. main.cpp could use the initial values of both global variables, but updating those global variables with new values later seemed to be completely invisible to main.cpp (I am wondering if these globals were implicitly read-only, but this may just be lack of understanding/user error on my part). Aside from this behavior, common wisdom is that globals shouldn't be used unless absolutely necessary, and it seems weird to have to use globals for something so seemingly simple. Is there no simpler/better way?
Thanks!