简体   繁体   中英

Call non-static member from WndProc

Anyone know how to call non-static member from WndProc?

Here is my WndProc prototype:

LRESULT CALLBACK System::Windows::Forms::Control::WndProc(HWND hWnd,
                      UINT message, WPARAM wParam, LPARAM lParam)            
{

    switch (message)
    {
    case WM_CREATE:
        this->OnCreate(new EventArgs(hWnd, message, wParam, lParam));

        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}

And defination:

class LIBMANAGED_API Control
{
protected:
    HWND hWnd;
    static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
...
};

This is wrong on so many levels. What do you really want to achieve? Just from this piece of code, there's not enough info.

First, you declare this method using a mixture of C and managed C++. It either

protected virtual void WndProc(Message m) // Managed C++

as you see, NOT static method, LRESULT, HWND and so on, or

LRESULT CALLBACK WindowProc(
  _In_ HWND   hwnd,
  _In_ UINT   uMsg,
  _In_ WPARAM wParam,
  _In_ LPARAM lParam
);

as you can see, no System namespace.

Second, where are your clases defined? I suspect you should override your method, using Managed C++, see MSDN .

You were not that far as you are already processing the WM_CREATE message.

The trick is to pass an object pointer at creation time and store it in the Window itself with SetWindowLongPtr in the WM_CREATE or WM_NCCREATE message. The you can extract it with GetWindowLongPtr and access your object from the window procedure.

Window creation (say MyWnd myWnd is the C++ object that will represent the window):

HWND hWnd = CreateWindow( m_pszClassName, "Name", WS_VISIBLE | WS_OVERLAPPED,
    x, y, w, h, NULL, NULL, hInst, &myWnd);

Window procedure:

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)            
{
    MyWnd *myWnd;
    myWnd = (MyWnd *) GetWindowLongPtr(hWnd, GWLP_USERDATA); /* to use it outside WM_CREATE */

    switch (message)
    {
    case WM_CREATE:
        CREATESTRUCT * pcs = (CREATESTRUCT*)lParam;
        MyWnd* myWnd= (MyWnd*) pcs->lpCreateParams;
        SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG_PTR) myWnd);

        myWnd->OnCreate(new EventArgs(hWnd, message, wParam, lParam));

        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM