如何在VC++中加入自定义消息,我的做法:
这里我以一个对话框为例子,环境:VS 2008,新建一个工程,选择对话框:以编译器给出的对话框为蓝本,自己新建一个按钮如图:
![](https://i-blog.csdnimg.cn/blog_migrate/57610e4a8dcb7e67bfa5b507d83461e8.png)
把名字改成如图的,其他比如ID什么的都不改了,默认。
1 首先在ownermessageDlg.h中定义消息:例如
define WM_MYMESSAGE (WM_USER+100)
2 在.H文件中,加入消息响应函数,如:
afx_msg LRESULT OnMyMessage(WPARAM w,LPARAM l);
该函数有规定的格式:
afx_msg LRESULTFunction_Name(WPARAM w,LPARAM l);
3 在ownermessageDlg.cpp中加入消息响应宏
在响应该消息的类中,在消息响应块中,
BEGIN_MESSAGE_MAP(CownermessageDlg,CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
END_MESSAGE_MAP()
加入以下语句:
ON_MESSAGE(WM_MYMESSAGE,OnMyMessage)
成为如下样式:
BEGIN_MESSAGE_MAP(CownermessageDlg,CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_MESSAGE(WM_MYMESSAGE,OnMyMessage)
END_MESSAGE_MAP()
4 在.CPP文件中,编辑消息响应函数,如下:
LRESULTCownermessageDlg::OnMyMessage(WPARAM wParam, LPARAM lParam) {
MessageBox(_T("MyMessage!"));
return1;
}
5.在对话框中为新增的按钮添加单击响应,ownermessageDlg.cpp中的MESSAGE_MAP变成:
BEGIN_MESSAGE_MAP(CownermessageDlg,CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_MESSAGE(WM_MYMESSAGE,OnMyMessage)
ON_BN_CLICKED(IDC_BUTTON1,&CownermessageDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
voidCownermessageDlg::OnBnClickedButton1()
{
PostMessage(WM_MYMESSAGE,IDC_BUTTON1);
}
PostMessage(……)这个就是响应WM_MYMESSAGE消息的,其实这样写也可以:
PostMessage(WM_MYMESSAGE);
我们来看看这个消息的函数原型:
在CWnd::PostMessage中定义
BOOL PostMessage (
UINTmessage,
WPARAMwParam = 0,
LPARAMlParam = 0
);
Parameters:
message
Specifies themessage to be posted.
wParam
Specifiesadditional message information. The content of this parameter depends on themessage being posted.
lParam
Specifiesadditional message information. The content of this parameter depends on themessage being posted.
Return Value
Nonzero if the messageis posted; otherwise 0.
所以一般的当点击时,消息触发就会发送一个WM_MYMESSAGE消息,故而调用CownermessageDlg::OnMyMessage(WPARAMwParam, LPARAM lParam)这个函数。