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); // 不等处理完就返回
}
posted @   double64  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示