通過嘗試有兩種方案可以解決這個問題,第一種方案是通過PreTranslateMessage函數在調度消息之前對消息類型進行篩選,第二種方案是重載CButton類,在重載后的類CForTestButton中新增ON_WM_LBUTTONDOWN消息以及ON_WM_LBUTTONUP消息。
第一種方案
實現原理也挺簡單,在消息調度函數PreTranslateMessage函數中攔截Button按鈕的句柄,之后在對應大括號內調用相關功能塊即可。核心源碼如下:
…… ……
BOOL CTestButtonDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_LBUTTONDOWN)
{
if(pMsg->hwnd == GetDlgItem(IDC_BTN_FOR_TEST)->m_hWnd)
{
MessageBox("Button按鈕按下");
// 在此調用Button按鈕按下的操作
}
}
if(pMsg->message == WM_LBUTTONUP)
{
if(pMsg->hwnd == GetDlgItem(IDC_BTN_FOR_TEST)->m_hWnd)
{
MessageBox("Button按鈕抬起");
// 在此調用Button按鈕抬起的操作
}
}
}
…… ……
其中,“IDC_BTN_FOR_TEST”表示待按下的按鈕ID。
第二種方案
自定義一個類CForTestButton類繼承CButton類,在繼承類CForTestButton類中新增ON_WM_LBUTTONDOWN()消息和ON_WM_LBUTTONUP()消息。ForTestButton.h頭文件中新增的源碼如下:
…… …… afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); DECLARE_MESSAGE_MAP() …… ……
ForTestButton.cpp源文件中新增的源碼如下:
…… ……
BEGIN_MESSAGE_MAP(CForTestButton, CButtion)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
END_MESSAGE_MAP()
…… ……
…… ……
void CForTestButton::OnLButtonDown(UINT nFlags, CPoint point)
{
CRect rcJog;
this->GetClientRect(&rcJog);
if(rcJog.PtInRect(point))
{
MessageBox("Button按鈕按下");
}
}
void CForTestButton::OnLButtonUp(UINT nFlags, CPoint point)
{
CRect rcJog;
this->GetClientRect(&rcJog);
if(rcJog.PtInRect(point))
{
MessageBox("Button按鈕抬起");
}
}
…… ……
