当鼠标停留在程序窗口一定时间后,会产生一个WM_MOUSEHOVER消息;当鼠标离开程序窗口后,会产生一个WM_MOUSELEAVE消息。那如何才能使窗口响应这两个消息呢?按下面的步骤,即可让指定的窗口能捕获并响应WM_MOUSEHOVER和WM_MOUSELEAVE消息了:
2、在窗口类的cpp文件中添加:
3、用
ON_MESSAGE
添加消息映射:
4、在OnMouseMove响应函数中,调用_TrackMouseEvent(),设置捕获WM_MOUSEHOVER和WM_MOUSELEAVE消息请求:
(2) 让一个相对独立的窗口捕获WM_MOUSEHOVER和WM_MOUSELEAVE消息,直接按上述方法就可以了。如果让子窗口CButton、CStatic等来捕获,则需要在基类的基础上派生出一个子类,在子类中按上述办法来实现就行了。
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 )
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.