MFC中消息机制的应用

我现在正在看的网管程序应用了大量的消息机制,而以前我也看到过不少,不过一直没学,现在把程序分析了一下,总结了一下消息机制的应用方法:

一.定义消息

    在头文件中定义消息:

         #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();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章