const UINT WM_MYMSG = WM_USER + 100;(建議 ≥ WM_USER+100 避免衝突)afx_msg LRESULT OnMyMsg(WPARAM, LPARAM);AFX_MSG 區塊加入宣告ON_MESSAGE(WM_MYMSG, OnMyMsg)// 頭檔
afx_msg void OnMyMsg();
ON_MESSAGE_VOID(WM_MYMSG, OnMyMsg)
// 實作
void CMyClass::OnMyMsg() { /* ... */ }
// 1. 定義訊息(建議在共用頭檔)
#define WM_MY_MESSAGE (WM_USER + 100)
// 2. 處理函數簽名
LRESULT CMainFrame::OnMyMessage(WPARAM wParam, LPARAM lParam) {
// TODO: 處理邏輯
return 0;
}
// 3. 類別宣告
class CMainFrame : public CMDIFrameWnd {
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT);
afx_msg void OnTimer(UINT);
afx_msg LRESULT OnMyMessage(WPARAM, LPARAM); // 新增
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
// 4. 訊息對應
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
ON_WM_TIMER()
ON_MESSAGE(WM_MY_MESSAGE, OnMyMessage) // 新增
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT WM_MY_MSG = RegisterWindowMessage(_T("MyUniqueMessageName"));
// 對應宏改為 ON_REGISTERED_MESSAGE(WM_MY_MSG, OnMyMessage)
PostMessage(WM_MY_MESSAGE, 0, 0);
SendMessage(WM_MY_MESSAGE, 0, 0);
DWORD result;
SendMessageTimeout(hWndTarget, WM_MY_MESSAGE, 0, 0,
SMTO_ABORTIFHUNG | SMTO_NORMAL,
TIMEOUT_INTERVAL, &result);
關鍵:取得目標類別指標 → 呼叫 PostMessage / SendMessage
void CMainFrame::OnTest() {
CView* pView = GetActiveView();
if (pView) pView->PostMessage(WM_MY_MESSAGE, 0, 0);
}
void CMainFrame::OnTest() {
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;
CMDIChildWnd* pChild = (CMDIChildWnd*)pFrame->GetActiveFrame();
CView* pView = pChild->GetActiveView();
if (pView) pView->PostMessage(WM_MY_MESSAGE, 0, 0);
}
void CMessageView::OnTest() {
CFrameWnd* pFrame = GetActiveFrame();
if (pFrame && pFrame != this) pFrame->PostMessage(WM_MY_MESSAGE, 0, 0);
}
MessageTestDialog,按鈕處理函數 OnDialogTestMessage.h 定義:static UINT WM_MY_MESSAGE = RegisterWindowMessage(_T("Message"));CMessageView 加入 ON_REGISTERED_MESSAGE、處理函數、BOOL test 旗標、OnDraw 顯示「訊息響應!」#include "TestDialog.h",菜單命令彈出對話方塊WM_USER + 100,或用 RegisterWindowMessage 保證全域唯一SendMessageTimeout 防死鎖PostMessageLRESULT OnXxx(WPARAM, LPARAM) 或 void OnXxx()