This question already has an answer here:
- Win32 WndProc as class member 3 answers
I'm trying to create a class that includes the WndProc, but I'm getting an error :
Error 2 error C2440: '=' : cannot convert from 'LRESULT (__stdcall Client::* )(HWND,UINT,WPARAM,LPARAM)' to 'WNDPROC'
I searched the web for it, and seen that you need to make the WndProc static, but then, it compiles and everything is great, though if I want to change something, it doesnt let me :
Error 3 error C2352: 'Client::CreateMen' : illegal call of non-static member function
(CreateMen is a function in the class that creates the menu, using HMENU and such).
this is my function title:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
What can I do? I'm really confused...
Thanks!
Unfortunately you cannot use a class function as a wndproc because as the compiler tries to tell you the calling convention differs, even though the two functions have the same signature, a class function expects the this pointer to be passed to it. On 64 bit builds it will expect it to be in the RCX/ECX registry while on 32 bit builds it will expect the this pointer to be the last argument pushed on the stack. The window code won't do that when calling your WndProc essentially turning this into a function call on a garbage pointer.
What you can do is make a static method that does something like the following:
I haven't tested this, so it might have some bugs, but let me know if you have any problems with it and I'll refine it if need be.
A non-static class method has a hidden
this
parameter. That is what prevents the method from being used as a WndProc (or any other API callback). You must declare the class method asstatic
to remove thatthis
parameter. But as you already noticed, you cannot access non-static members from a static method. You need a pointer to the object in order to access them.In the specific case of a WndProc callback, you can store the object pointer in the HWND itself (using either
SetWindowLong/Ptr(GWL_USERDATA)
orSetProp()
), then your static method can retrieve that object pointer from thehWnd
parameter (usingGetWindowLong/Ptr(GWL_USERDATA)
orGetProp()
) and access non-static members using that object pointer as needed. For example: