1. 程式人生 > >VC++自定義訊息的傳送與接收的方法實現

VC++自定義訊息的傳送與接收的方法實現

訊息傳遞的方法一:使用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;
}


訊息傳遞的方法二:使用ON_REGISTERED_MESSAGE
使用ON_REGISTERED_MESSAGE註冊訊息,必須配合
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
對於訊息的傳送者-MyMessageDlg,
在其MyMessageDlg.h中,只要
定義static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
就可以了。
在其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中不要定義
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
應該把這個定義放到MessageTestView.cpp中,要不會出現: redefinition
在其MessageTestView.h中只要定義訊息對映函式
protected:
 //{{AFX_MSG(CMessageTestView)
 afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
在其MessageTestView.cpp中,先定義
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
接著註冊訊息:
BEGIN_MESSAGE_MAP(CMessageTestView, CEditView)
 //{{AFX_MSG_MAP(CMessageTestView)
        ON_REGISTERED_MESSAGE(WM_MY_MESSAGE,OnMyMessage)
 //}}AFX_MSG_MAP
最後新增訊息響應的函式實現:
LRESULT CMessageTestView::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
 MessageBox("OnMyMessage!");
 return 0;
}
----------------------------------------------------------------
比較兩種方法,只是略有不同。但也要小心謹慎,以免出現接收不到訊息的情況。
-------------------------------------------------------------------
其他注意事項:
傳送訊息的-MyMessageDlg.cpp前也要定義
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
接受訊息的-MessageTestView.cpp前也要定義
static UINT WM_MY_MESSAGE=RegisterWindowMessage("Message");
RegisterWindowMessage("Message")中""的內容是什麼不重要,寫什麼都可以,但是
傳送者與接受者必須是一樣的內容,例如:"Message"