是的,你可以自定义消息并执行对应的消息处理函数。在 MFC 中,你可以使用 `RegisterWindowMessage` 函数为你的自定义消息生成一个唯一的消息码,并在消息映射表中映射这个消息码到相应的处理函数。 以下是一个简单的示例,假设你要定义一个自定义消息 `WM_MY_CUSTOM_MESSAGE`: ```cpp // 在头文件中定义自定义消息码 #define WM_MY_CUSTOM_MESSAGE (WM_USER + 1) class CMyDialog : public CDialog { // 构造函数、析构函数等成员的声明 // 消息映射 protected: afx_msg void OnMyCustomMessage(WPARAM wParam, LPARAM lParam); // 声明自定义消息处理函数 DECLARE_MESSAGE_MAP() }; ``` 在实现文件中,使用 `BEGIN_MESSAGE_MAP` 宏和 `END_MESSAGE_MAP` 宏将消息映射到相应的处理函数: ```cpp // MyDialog.cpp #include "MyDialog.h" BEGIN_MESSAGE_MAP(CMyDialog, CDialog) ON_MESSAGE(WM_MY_CUSTOM_MESSAGE, OnMyCustomMessage) // 映射自定义消息到 OnMyCustomMessage 函数 // 其他消息映射... END_MESSAGE_MAP() ``` 然后实现消息处理函数: ```cpp // MyDialog.cpp void CMyDialog::OnMyCustomMessage(WPARAM wParam, LPARAM lParam) { // 处理自定义消息的代码 AfxMessageBox(_T("Custom Message Received!")); } ``` 在需要发送自定义消息的地方,可以使用 `PostMessage` 函数: ```cpp // 在需要的地方发送自定义消息 PostMessage(WM_MY_CUSTOM_MESSAGE, 0, 0); ``` 这样,当调用 `PostMessage` 时,`OnMyCustomMessage` 函数就会被调用。确保消息的参数类型和数量与消息处理函数的声明相匹配。 |
|