Trying to return value from Message c++ mfc

2019-07-16 06:15发布

问题:

i'm using c++ mfc and declare message in my dlg:

LRESULT CMyWnd2::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
    wParam=5;
    lParam=6;
    return 0;
}

using code:

WPARAM w=0;
LPARAM l=0;
SendMessage(hwnd,messageId,w,l);
cout<<w<<l<<endl;

print:

0
0

how can i change the values of w / l parameters?

回答1:

LRESULT CMyWnd2::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
    *((WPARAM*)wParam)=5;
    *((LPARAM*)lParam)=6;
    return 0;
}


WPARAM w=0;
LPARAM l=0;
SendMessage(hwnd,messageId,(WPARAM)&w,(LPARAM)&l);
cout<<w<<l<<endl;


回答2:

A function can not change the parameters passed in by value.

However, you can pass a pointer to whatever data structure you want in LPARAM, and modify that data structure in your message handler.

Here is how you can use it:

int myValueToBeUpdated = 0;
SendMessage(hwnd, messageId, 0, (LPARAM)&myValueToBeUpdated);
cout << myValueToBeUpdated << endl;

and the message handler:

LRESULT CMyWnd2::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
    int* p = (int*)lParam;
    *p = 42;
    return 0;
}


标签: c++ winapi mfc