WindowProc in a class - function and pointer problem

Diggory diggsey at googlemail.com
Wed May 22 14:22:50 PDT 2013


On Wednesday, 22 May 2013 at 20:25:40 UTC, Simen Kjaeraas wrote:
> On 2013-05-22, 21:30, D-sturbed wrote:
>
>> Hello, is there a way to wrap a WindowProc (so "LRESULT 
>> WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM 
>> lParam) nothrow") in a class and to link it to a WindowClass 
>> without puting it as "static" ?
>>
>> Because defacto every datum used in the WindowProc must also 
>> be static.
>> The problem technically is that if "static" is not specified, 
>> the compiler won't allow this: "MyWinClass.lpfnWndProc = 
>> &TheWindowProcInMyClass".
>>
>> I've also tried this: "MyWinClass.lpfnWndProc = 
>> (&TheWindowProcInMyClass).funcptr" but, while it compiles, it 
>> drastically fails at the run-time...
>
> Not possible, no. What you *can* do is have some way to 
> translate from
> hwnd to class instance, and fetch the right instance inside the 
> static
> wndProc to call a member function on that.

If you are only going to have one window you can store the "this" 
pointer in a global variable.

If you want to have multiple windows each with messages going to 
an instance of a class, you need to do the following:
- Specify the "this" pointer as the lpParam argument to 
CreateWindow
- Hook up a static WndProc function
- Have the static function handle a WM_NCCREATE message as 
follows:
     - Cast the "lParam" parameter to a CREATESTRUCT* and retrieve 
the "this" pointer from the "lpCreateParams" member.
     - Use "SetWindowLongPtr" to set the GWLP_USERDATA property of 
the window "hwnd" to the "this" pointer
- Have the static function handle all messages as follows:
     - Use "GetWindowLongPtr" to get the GWLP_USERDATA property of 
the window "hwnd" to get the "this" pointer
     - Pass the message on to a non-static WndProc in the class 
using the discovered "this" pointer

You also need to make sure that there is a separate reference to 
the class instance for as long as the window exists, because the 
garbage collector will not scan the window properties and so may 
think the object is garbage otherwise.


More information about the Digitalmars-d-learn mailing list