freesoft
freesoft

Reputation: 57

Calling a member pointer to function that points to a C function within a windows procedure make app crash

I have this main.cpp code:

#include <windows.h>
#include <commctrl.h>
#include <process.h>
#include <stdio.h>

void click(){printf("button clicked\n");}

struct WindowData
{
    void (*PF)();        

    WindowData():PF(NULL){}
};

LRESULT CALLBACK dialog_procedure(HWND h,UINT u,WPARAM w,LPARAM l)
{
    WindowData *wp=(WindowData*)GetWindowLongPtr(h,GWL_USERDATA);

    switch(u)
    {
        case WM_COMMAND:
            if(LOWORD(w)==BN_CLICKED)
            if(wp && wp->PF)wp->PF();
        break;
    }
    return DefWindowProc(h,u,w,l);
}

int main()
{

    WindowData * windowdata=new WindowData();

    windowdata->PF=click; //bind function

    HWND window=CreateWindow(WC_DIALOG,"App",WS_VISIBLE|WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,0,0,300,300,0,0,0,windowdata);
    HWND button=CreateWindow(WC_BUTTON,"Click",WS_VISIBLE|WS_CHILD,0,0,100,30,0,0,0,0);

    SetWindowLongPtr(window,GWL_WNDPROC,(LONG_PTR)dialog_procedure);



    MSG msg;

    while(GetMessage(&msg,NULL,0,0)>0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 1;

}

Now i build all with: c++ main.cpp -lcomctl32

Run the executable

but when i press the "Click" button, PF is never called...

calling windowdata->PF() after binding, works;

calling click() anywhere in dialog_procedure works;

calling wp->PF() anywhere in dialog_procedure make app crash;

where am I wrong?

Upvotes: 0

Views: 138

Answers (1)

Alex F
Alex F

Reputation: 43331

Add this line to main function:

SetWindowLongPtr(window,GWL_USERDATA,(LONG_PTR)windowdata); 

Upvotes: 2

Related Questions