我現在正在看的網管程序應用了大量的消息機制,而以前我也看到過不少,不過一直沒學,現在把程序分析了一下,總結了一下消息機制的應用方法:
一.定義消息
在頭文件中定義消息:
#define WM_SEND_A_MESSAGE WM_USER+1
二.發送消息
PostMessage(WM_SEND_A_MESSAGE,wParam,lParam);
三.定義消息響應函數
1.在頭文件中聲明消息響應函數
afx_msg LRESULT OnReceiveMessage(WPARAM wParam , LPARAM lParam);
2.在MESSAGE_MAP中關聯消息響應函數:
ON_MESSAGE( WM_SEND_A_MESSAGE , OnReceiveMessage)
3.定義函數體,對消息進行處理。
====================傳遞參數類型================
1.整形(直接傳遞,不進行轉換)
int temp=24;
PostMessage(WM_SEND_A_MESSAGE,temp,0);
處理: int i=wParam;
2.指針類型
int* tem=new int(23);
PostMessage(WM_SEND_A_MESSAGE,reinterpret_cast<WPARAM>(tem),0);
處理:int* i=reinterpret_cast<int*>(wParam);
3.結構體指針
1)定義結構體
typedef struct ST_A
{
ST_A()
{
a=1;
}
~ST_A()
{
a=0;
}
int a;
CString str;
}* PSTA;
2)聲明結構體對象
PSTA ps=new ST_A;//非 new PATA!!(開始一直出問題就是這個原因)
ps->a=8;
ps->str="hello,message!";
3)發送消息
PostMessage(WM_SEND_A_MESSAGE,reinterpret_cast<WPARAM>(ps),0);
4)處理:
PSTA pst=reinterpret_cast<PSTA>(wParam);
========================附源代碼=========================
void CPostMessageDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知處理程序代碼
int temp=24;
int* tem=new int(23);
PSTA ps=new ST_A;
ps->a=8;
ps->str="hello,message!";
//PostMessage(WM_SEND_A_MESSAGE,temp,0);
// PostMessage(WM_SEND_A_MESSAGE,reinterpret_cast<WPARAM>(tem),0);
PostMessage(WM_SEND_A_MESSAGE,reinterpret_cast<WPARAM>(ps),0);
}
afx_msg LRESULT CPostMessageDlg::OnReceiveMessage(WPARAM wParam , LPARAM lParam)
{
int i=wParam;
int* i=reinterpret_cast<int*>(wParam);
PSTA pst=reinterpret_cast<PSTA>(wParam);
CString st;
st.Format("%d",*i);
//st.Format("%d",pst->a);
AfxMessageBox(st);
//AfxMessageBox(pst->str);
return afx_msg LRESULT();
}