对话框上的按钮本身只能添加单击双击时间,不能响应鼠标按下与弹起消息,可以通过两种方法实现:
1.重载CButton类,将该类子类化
在工程中添加一个新类CMyButton,基类为CButton。
在对话框MyDlg中为IDC_BUTTON添加变量,在变量类型里选择CMyButton,变量名自定义,如m_myButton。添加函数OnDown与OnUp函数响应按钮按下与弹起消息
在Class name中选择CMyButton,然后添加WM_LBUTTONUP,WM_LBUTTONDOWN消息映射函数。添加代码如下:
void CMyButton::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
((CMyDlg*)GetParent())->OnUp(this->GetDlgCtrlID());
CButton::OnLButtonUp(nFlags, point);
}
void CMyButton::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
((CMyDlg*)GetParent())->OnDown(this->GetDlgCtrlID());
CButton::OnLButtonDown(nFlags, point);
}
然后MyDlg中实现函数
void CMyDlg::OnDown( UINT nID )
{
Switch(nID)
case IDC_BUTTON:
break;
}
void CMyDlg::OnUp( UINT nID )
{
...
}
2.重载Dialog的PreTranslateMessage函数
BOOL CTestDlgDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if(pMsg-> message == WM_LBUTTONDOWN)
{
if(WindowFromPoint(pMsg-> pt) == GetDlgItem(IDC_BUTTON1))
{
}
}
else if(pMsg-> message == WM_LBUTTONUP)
{
if(WindowFromPoint(pMsg-> pt) == GetDlgItem(IDC_BUTTON1))
{
//AfxMessageBox( "Hello ");
}
}
return CDialog::PreTranslateMessage(pMsg);
}