對話框類 MyMessageDlg 向視圖類 MessageTestView 發送自訂訊息。
// MyMessageDlg.h
#define WM_MY_MESSAGE (WM_USER + 100)
// MyMessageDlg.cpp
#include "MainFrm.h"
void MyMessageDlg::OnButtonMsg() {
CMainFrame* pMF = (CMainFrame*)AfxGetApp()->m_pMainWnd;
CView* active = pMF->GetActiveView();
if (active) active->PostMessage(WM_MY_MESSAGE, 0, 0);
}
// MessageTestView.h
#define WM_MY_MESSAGE (WM_USER + 100)
protected:
afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
// MessageTestView.cpp
BEGIN_MESSAGE_MAP(CMessageTestView, CEditView)
ON_MESSAGE(WM_MY_MESSAGE, OnMyMessage)
END_MESSAGE_MAP()
LRESULT CMessageTestView::OnMyMessage(WPARAM, LPARAM) {
MessageBox("OnMyMessage!");
return 0;
}
// MyMessageDlg.h
static UINT WM_MY_MESSAGE = RegisterWindowMessage("MyUniqueMessageString");
// 其餘相同
// MessageTestView.h - 僅宣告處理函數,不定義 static 變數
protected:
afx_msg LRESULT OnMyMessage(WPARAM, LPARAM);
DECLARE_MESSAGE_MAP()
// MessageTestView.cpp - 這裡定義 static 變數,避免重複定義錯誤
static UINT WM_MY_MESSAGE = RegisterWindowMessage("MyUniqueMessageString");
BEGIN_MESSAGE_MAP(CMessageTestView, CEditView)
ON_REGISTERED_MESSAGE(WM_MY_MESSAGE, OnMyMessage)
END_MESSAGE_MAP()
LRESULT CMessageTestView::OnMyMessage(WPARAM, LPARAM) {
MessageBox("OnMyMessage!");
return 0;
}
| 特性 | ON_MESSAGE | ON_REGISTERED_MESSAGE |
|---|---|---|
| 訊息 ID 來源 | WM_USER + offset | RegisterWindowMessage("字串") 系統分配唯一值 |
| 跨進程能力 | 否 (僅進程內) | 是 (全系統唯一) |
| ID 衝突風險 | 高 (不同模組可能用同 offset) | 極低 (字串唯一) |
| 定義位置要求 | 雙方頭檔各自定義 | 發送端 .h、接收端 .cpp 定義 |
| 宏巨集 | ON_MESSAGE | ON_REGISTERED_MESSAGE |
RegisterWindowMessage 字串參數雙方必須完全相同 (大小寫敏感)RegisterWindowMessageCMainFrame* pMF = (CMainFrame*)AfxGetMainWnd(); (原碼 AfxGetApp()->m_pMainWnd 亦可但較繞)PostMessage 非同步投遞;SendMessage 同步阻塞