当鼠标停留在程序窗口一定时间后,会产生一个WM_MOUSEHOVER消息;当鼠标离开程序窗口后,会产生一个WM_MOUSELEAVE消息。那如何才能使窗口响应这两个消息呢?按下面的步骤,即可让指定的窗口能捕获并响应WM_MOUSEHOVER和WM_MOUSELEAVE消息了:
1、在窗口类的头文件中添加:
afx_msg void OnMouseHover(); afx_msg void OnMouseLeave(); BOOL m_bTrackLeave; // 捕获设置标记
void CXXXWnd::OnMouseHover() { MessageBox( "鼠标已进入 "); m_bTrackLeave = FALSE; } void CXXXWnd::OnMouseLeave() { MessageBox( "鼠标已离开 "); m_bTrackLeave = FALSE; }
ON_MESSAGE( WM_MOUSEHOVER, OnMouseHover ) ON_MESSAGE( WM_MOUSELEAVE, OnMouseLeave )
void CXXXWnd::OnMouseMove(UINT nFlags, CPoint point) { if (!m_bTracking) { // 鼠标移入窗时,请求WM_MOUSEHOVER和WM_MOUSELEAVE 消息 TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); tme.hwndTrack = m_hWnd; tme.dwFlags = TME_LEAVE|TME_HOVER; tme.dwHoverTime = 1; m_bTracking = _TrackMouseEvent(&tme); } CWnd::OnMouseMove(nFlags, point); }
5、相关说明
(1) 调用一次_TrackMouseEvent只能请求一次WM_MOUSEHOVER和WM_MOUSELEAVE消息,所以要放到OnMouseMove中多次请求,msdn中的相关解释:
The _TrackMouseEvent function posts messages when the mouse pointer leaves a window or hovers over a window for a specified amount of time. This function calls TrackMouseEvent if it exists, otherwise it emulates it. All tracking requested by TrackMouseEvent is canceled when this message is generated. The application must call TrackMouseEvent when the mouse reenters its window if it requires further tracking of mouse hover behavior.