VC消息传递(对话框间传递参数)

以下用一个自创的对话框类(MyMessageDlg)向视图类(MessageTestView)
发送自定义消息为例,说明这两种不同方法的自定义消息的

消息传递的方法一:使用ON_MESSAGE
使用ON_MESSAGE响应消息,必须配合定义消息#define WM_MY_MESSAGE (WM_USER+100)

对于发送消息者-MyMessageDlg,
在其MyMessageDlg.h中,定义#define WM_MY_MESSAGE (WM_USER+100)
在其MyMessageDlg.cpp中要先添加:#i nclude "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(CMessageTestView)
 afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
在其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;
}

原文地址:https://www.cnblogs.com/LJWJL/p/4344651.html