测试鼠标是否在窗口内,以及鼠标的离开
以下给出两种跟踪鼠标是否在窗口内的方法
一、使用SetCapture(),OnMouseMove()等判断鼠标位置
void CMyDlg::OnMouseMove(UINTnFlags,CPointpoint)
{
CRect rect;
GetClientRect(&rect);
if(!rect.PtInRect(point))
{
strWnd = "NO";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
ReleaseCapture();
}
else
{
strWnd = "YES";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
SetCapture();
}
CDialog::OnMouseMove(nFlags, point)
}
二、使用TrackMouseEvent()
在鼠标离开窗口时发送WM_MOUSELEAVE消息,使用TrackMouseEvent()可以判断鼠标的停留,并发送WM_MOUSEHOVER消息
//设置一个状态量用于记录和标识鼠标是否在窗口内//
BOOL m_bMouseTracking;
//处理鼠标移动消息
void CMouseLeaveDlg::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
/*CRect rect;
GetClientRect(&rect);
if(!rect.PtInRect(point))
{
strWnd = "NO";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
m_InWindow=FALSE;
ReleaseCapture();
}
else
{
strWnd = "YES";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
m_InWindow=TRUE;
SetCapture();
}*/
//接收到WM_MOUSEMOVE,而m_bMouseTracking为假时,鼠标进入窗口。
//设置_TrackMouseEvent
if(!m_bMouseTracking)
{
TRACKMOUSEEVENT tme;
tme.cbSize=sizeof(TRACKMOUSEEVENT);
//监控鼠标离开
tme.dwFlags=TME_LEAVE;
tme.hwndTrack=this->m_hWnd;
if(::_TrackMouseEvent(&tme))
{
m_bMouseTracking=TRUE;
strWnd = "YES";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
}
}
CDialog::OnMouseMove(nFlags, point);
}
////处理WM_MOUSELEAVE消息////消息处理函数声明
afx_msg LRESULT OnMouseLeave(WPARAM wParam,LPARAM lParam);
//消息映射
ON_MESSAGE(WM_MOUSELEAVE,OnMouseLeave)
//处理函数定义
LRESULT CMouseLeaveDlg::OnMouseLeave(WPARAM wParam,LPARAM lParam)
{
////其他鼠标离开时的操作/
///重置状态量
m_bMouseTracking = FALSE;
strWnd = "NO";
CDC *pDC = GetDC();
pDC->TextOut(0,0,strWnd);
return TRUE;
}