OnMouseHover()和OnMouseLeave()(让窗口捕获并响应WM_MOUSEHOVER和WM_MOUSELEAVE消息)

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

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

 

	afx_msg void OnMouseLeave();
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);


2、在窗口类的cpp文件中添加:

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

 

3、用ON_MESSAGE添加消息映射:

//vs2008以上添加以下代码
ON_MESSAGE( WM_MOUSEHOVER, OnMouseHover )  
ON_MESSAGE( WM_MOUSELEAVE, OnMouseLeave )  

//vs2003添加以下代码
//自定消息
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);  
}  



 

你可能感兴趣的:(windows编程)