Win32 - WndProc as class member, pointer to class instance is always nullptr

Viewed 37

I am trying to wrap WndProc as a private class member. I read the trick is to use two WndProc functions, one of them static. I set cbWndExtra to the size of a LONG_PTR and tried setting and getting the pointer to my class instance using SetWindowLongPtr and GetWindowLongPtr. I am then checking if it's a nullptr and calling the second WndProc if it's not. But for some reason pApplication always is a nullptr so my application is always running the DefWindowProc without running my own WndProc.

Application.h

private:
    static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept;
    LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept;

Application.cpp

LRESULT CALLBACK Application::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept
{
    Application* pApplication;

    if (msg == WM_NCCREATE)
    {
        pApplication = static_cast<Application*>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);
        SetWindowLongPtr(hWnd, GWL_USERDATA, reinterpret_cast<LONG_PTR>(pApplication));
    }
    else
    {
        pApplication = reinterpret_cast<Application*>(GetWindowLongPtr(hWnd, GWL_USERDATA));
    }

    if (pApplication)
        return pApplication->HandleMsg(hWnd, msg, wParam, lParam);

    return DefWindowProc(hWnd, msg, wParam, lParam);
}
1 Answers

Solution: I accidentally passed a nullptr instead of this to CreateWindowA which obviously didn't even set the lParam so I wasn't able to retrieve it afterwards.

Related