这段时间在开发一个工装的测试程序,其中有个功能是:当鼠标移动到一个测试项的按钮时,给出这个测试按钮对应的管脚。
简单的说就是在鼠标移动到一个按钮时,在一个区域中显示一个信息,移出按钮时,这个信息消失。
完成了,做个一种总结吧:
1.继承CButton生成CButtonEx消息WM_MOUSEMOVE消息。
2.在WM_MOUSEMOVE消息响应函数中添加消息跟踪
3.在对话框的类中重写PreTranslateMessage函数
代码如下:
1.CButtonEx中的代码
void CButtonEx::OnMouseMove(UINT nFlags, CPoint point)
{
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER|TME_LEAVE;
tme.dwHoverTime = HOVER_DEFAULT;
tme.hwndTrack = m_hWnd;
if (!_TrackMouseEvent(&tme))
{
AfxMessageBox("鼠标跟踪失败!");
}
CButton::OnMouseMove(nFlags, point);
}
2.CTestButtonRectDlg中的代码
增加一个CButtonEX控件的变量:
CButtonEx m_btnTest;
CRect m_rectPin;
BOOL CTestButtonRectDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE);// Set big icon
SetIcon(m_hIcon, FALSE);// Set small icon
// TODO: Add extra initialization here
GetDlgItem(IDC_STATIC)->GetWindowRect(&m_rectPin);
ScreenToClient(&m_rectPin);
m_rectPin.top +=13;
m_rectPin.bottom -=5;
m_rectPin.left +=5;
m_rectPin.right -=5;
m_hwndDlg = GetSafeHwnd();
return TRUE; // return TRUE unless you set the focus to a control
}
BOOL CTestButtonRectDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_MOUSELEAVE)
{
CBrush brush(RGB(239,230,222));//类似于界面的颜色
CClientDC dc(this);
CBrush *pOldBrush = dc.SelectObject(&brush);
dc.FillRect(&m_rectPin,&brush);
}
else if (pMsg->message == WM_MOUSEHOVER)
{
CBrush brush(RGB(140,140,120));
CClientDC dc(this);
CBrush *pOldBrush = dc.SelectObject(&brush);
dc.FillRect(&m_rectPin,&brush);
SetBkMode(dc,TRANSPARENT);
dc.TextOut(m_rectPin.left+35,m_rectPin.top+18,"p1");
ReleaseDC(&dc);
}
return CDialog::PreTranslateMessage(pMsg);
}