让窗口捕获并响应WM_MOUSEHOVER和WM_MOUSELEAVE消息

       当鼠标停留在程序窗口一定时间后,会产生一个WM_MOUSEHOVER消息;当鼠标离开程序窗口后,会产生一个WM_MOUSELEAVE消息。那如何才能使窗口响应这两个消息呢?按下面的步骤,即可让指定的窗口能捕获并响应WM_MOUSEHOVER和WM_MOUSELEAVE消息了:

        1、在窗口类的头文件中添加:

afx_msg   void   OnMouseHover();
afx_msg   void   OnMouseLeave();
BOOL   m_bTrackLeave;   // 捕获设置标记

        2、在窗口类的cpp文件中添加:
void   CXXXWnd::OnMouseHover()
{
          MessageBox( "鼠标已进入 ");
          m_bTrackLeave = FALSE;
}

void   CXXXWnd::OnMouseLeave()
{
          MessageBox( "鼠标已离开 ");
          m_bTrackLeave = FALSE;
}

        3、用 ON_MESSAGE添加消息映射:

ON_MESSAGE( WM_MOUSEHOVER, OnMouseHover )
ON_MESSAGE( WM_MOUSELEAVE, OnMouseLeave )

        4、在OnMouseMove响应函数中,调用_TrackMouseEvent(),设置捕获WM_MOUSEHOVER和WM_MOUSELEAVE消息请求:

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.

        (2) 让一个相对独立的窗口捕获WM_MOUSEHOVER和WM_MOUSELEAVE消息,直接按上述方法就可以了。如果让子窗口CButton、CStatic等来捕获,则需要在基类的基础上派生出一个子类,在子类中按上述办法来实现就行了。


你可能感兴趣的:(function,application)