MFC 自定义消息
▲ Demo 示例
新建基于对话框
的 Demo程序。
头文件:
// 自定义数据类型,用来测试消息数据传递
typedef struct tagStudent
{
CString Name;
int Age;
}Student_t;
// Dlg header
public:
afx_msg void OnBnClickedButtonCustomMsg();
afx_msg LRESULT OnCustomMessage(WPARAM wParam, LPARAM lParam); // 必须这种签名
private:
Student_t m_XiaoMing;
自定小的处理函数签名必须符合这样的参数:afx_msg LRESULT OnCustomMessage(WPARAM wParam, LPARAM lParam);
。
构造函数测试数据初始化:
CMFCCustomMsgDlg::CMFCCustomMsgDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_MFCCUSTOMMSG_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_XiaoMing.Name = _T("小明"); // 测试数据初始化
m_XiaoMing.Age = 12;
}
消息:
#define WM_CUSTOM_MSG (WM_USER + 1)
BEGIN_MESSAGE_MAP(CMFCCustomMsgDlg, CDialogEx)
ON_MESSAGE(WM_CUSTOM_MSG, &CMFCCustomMsgDlg::OnCustomMessage)
END_MESSAGE_MAP()
消息处理函数定义:
LRESULT CMFCCustomMsgDlg::OnCustomMessage(WPARAM wParam, LPARAM lParam)
{
Student_t* stuInfo = (Student_t*)wParam;
CString infoText;
infoText.Format(_T("姓名:%s\n年龄:%d\n额外信息:%ld\n"), stuInfo->Name, stuInfo->Age, lParam);
MessageBox(infoText);
return LRESULT();
}
按钮响应消息:
void CMFCCustomMsgDlg::OnBnClickedButtonCustomMsg()
{
//SendMessage(WM_CUSTOM_MSG, (WPARAM)(&m_XiaoMing), 100); // 等处理完才返回
PostMessage(WM_CUSTOM_MSG, (WPARAM)(&m_XiaoMing), 100); // 不等处理完就返回
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了