四: MFC消息总结

左心房为你撑大大i 提交于 2019-12-07 10:41:51

MFC消息总结

一:有句柄的消息发送

第一:在messageDlg界面里的操作

1,在窗口页面messageDlg.h填加消息定义

   #define WM_MY_MYMESSAGE (WM_USER+300)

2,在窗口页面messageDlg建立消息映射函数

  在messageDlg.h的protected:加上消息映射函数

  afx_msg LRESULT OnMyMsg(WPARAM wParam, LPARAM lParam);///////////

  在messageDlg.cpp的protected:加上消息映射

  BEGIN_MESSAGE_MAP(CmessageDlg, CDialog)
    ON_MESSAGE(WM_MY_MYMESSAGE, &CmessageDlg::OnMyMsg)////////////
  END_MESSAGE_MAP()

  消息映射函数写好:

  LRESULT CmessageDlg::OnMyMsg(WPARAM wParam, LPARAM lParam)
  {

           CString compname;
           compname=CString((wchar_t *)wParam); 

           或者
          TCHAR *f;
             f = (wchar_t *)wParam;
            ((CListBox *)GetDlgItem(IDC_LIST2))->AddString(compname);
   return 0;
  }

3,在在窗口页面messageDlg.h定义本窗口的句柄

  HWND hwad;

  在messageDlg.cpp中的OnInitDialog()获得句柄hwad = GetSafeHwnd();

4,在messageDlg.cpp里加上#include "msg.h"

5,将窗口句柄传到需要发送消息的界面里

void CmessageDlg::OnBnClickedButton1()
{

msg ms;
ms.possage(hwad);
}

第二: 在msg截面的操作

1,在msg.h界面里的public:加发送函数

   void possage(HWND hand);

2,在msg.cpp界面里上#include "messageDlg.h"和现在发送函数

  void msg::possage(HWND hand)
  {

               CString pp= _T("服务器端");
               BSTR   tmp   =   pp.AllocSysString();
               ::PostMessage(hand,WM_MY_MYMESSAGE,(WPARAM)tmp,4);或者

               ::SendMessage(hand,WM_MY_MYMESSAGE, (WPARAM)pp.GetBuffer(0), 4);//发送字符串
    ::PostMessage(hand,WM_MY_MYMESSAGE,0,0);
  }

第二:无句柄的消息发送

使用自定义函数响应消息,

定义消息#define WM_MY_MESSAGE (WM_USER+100)

对于发送消息者-MyMessageDlg,
在其MyMessageDlg.h中,定义#define WM_MY_MESSAGE (WM_USER+100)
在其MyMessageDlg.cpp中要先添加:#include "MainFrm.h"
因为使用了CMainFrame*定义对象。
并且要有测试消息的函数:
void MyMessageDlg::OnButtonMsg()
{
    // TODO: Add your control notification handler code here
    CMainFrame* pMF=(CMainFrame*)AfxGetApp()->m_pMainWnd; //先通过获取当前框架指针
    CView * active = pMF->GetActiveView();//才能获取当前视类指针
    if(active != NULL) //获取了当前视类指针才能发送消息
    active->PostMessage(WM_MY_MESSAGE,0,0);   //使用PostMessage发送消息
}

对于消息的接受者-MessageTestView,
在其MessageTestView.h中,也要定义#define WM_MY_MESSAGE (WM_USER+100)
并定义消息映射函数-OnMyMessage()
protected:
afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);
在其MessageTestView.cpp中,
先要声明响应消息:
BEGIN_MESSAGE_MAP(CMessageTestView, CEditView)
//{{AFX_MSG_MAP(CMessageTestView)
ON_MESSAGE(WM_MY_MESSAGE, OnMyMessage)
//}}AFX_MSG_MAP
再添加消息响应的函数实现:
LRESULT CMessageTestView::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
MessageBox("OnMyMessage!");
return 0;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!