2024年6月7日发(作者:)

MFC子窗口向父窗口发送消息

在MFC中,使用用户自定义消息,子窗口向父窗口发送消息过程、代码:

1)在resourse.h中增加定义:

static UINT WM_add_event_ok = RegisterWindowMessage(_T("User"));//测试

过,可行。

2)在父窗口的.h文件中,增加定义:

protected:

afx_msg LRESULT Onadd_event_ok(WPARAM wParam, LPARAM lParam);

两个参数:WPARAM wParam, LPARAM lParam类型不能更改。

3) 在父窗口的.cpp文件中增加消息映射部分:

ON_REGISTERED_MESSAGE(WM_add_event_ok,Onadd_event_ok)//测试通过,

可行。

4) 在父窗口的.cpp中定义消息处理函数的实现:

LRESULT 类名::Onadd_event_ok(WPARAM wParam, LPARAM lParam)

{

int c=10;

return 0;

}

5) 在需要发送消息处使用代码:

WPARAM a=8;

LPARAM b=9;

GetParent()->SendMessage(WM_add_event_ok,a,b);

//或使用如下代码发送消息:

HWND hwnd = ::GetParent(m_hWnd);

::SendMessage(hwnd,WM_add_event_ok,a,b);

//SendMessage(WM_add_event_ok,a,b);//在测试中,不使用GetParent()->的时

候,消息无法传递到父窗口的消息处理函数中,只有增加了GetParent()->后,消息才能

成功的发送。