實現步驟
- 在對話框類中重載
PreTranslateMessage(Class Wizard → Messages → PreTranslateMessage)。
- 在該函數中判斷消息類型與目標控件 ID。
完整代碼
BOOL CMouseDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_MOUSEMOVE) {
CWnd* pWnd = CWnd::FromHandle(pMsg->hwnd);
if (pWnd) {
int id = pWnd->GetDlgCtrlID();
CString tip;
switch (id) {
case IDC_BUTTON1: tip = _T("這是按鈕 1"); break;
case IDC_BUTTON2: tip = _T("這是按鈕 2"); break;
case IDC_BUTTON3: tip = _T("這是按鈕 3"); break;
default: tip.Empty();
}
if (!tip.IsEmpty()) {
GetDlgItem(IDC_STATIC_TIP)->SetWindowText(tip);
}
}
}
return CDialogEx::PreTranslateMessage(pMsg);
}
關鍵點
PreTranslateMessage 在消息分發前調用,可攔截所有控件的鼠標移動消息。
CWnd::FromHandle 獲取控件指針,GetDlgCtrlID 取得控件 ID。
- 靜態文本控件
IDC_STATIC_TIP 需設置 SS_NOTIFY 樣式以接收鼠標消息(可選)。
