Wednesday, December 5, 2007

Using TrackMouseEvent to find out when the Mouse Leaves from the Window

Using TrackMouseEvent is pretty simple. When the mouse enters the window you want to track, you call track mouse event telling it to inform you when the mouse leaves. When it does, it will send a WM_MOUSELEAVE message to that window.

Sample code:

// HotEdit.h changes
class CHotEdit : public CEdit
{
protected:
BOOL m_bMouseTracking;
afx_msg LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam);
...
};
// HotEdit.cpp changes
BEGIN_MESSAGE_MAP(CHotEdit, CEdit)
ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
END_MESSAGE_MAP()
CHotEdit::CHotEdit()
{
m_bMouseTracking = FALSE;
}
LRESULT CHotEdit::OnMouseLeave(WPARAM wParam, LPARAM lParam)
{
m_bMouseTracking = FALSE;
return TRUE;
}
void CHotEdit::OnMouseMove(UINT nFlags, CPoint point)
{
if (!m_bMouseTracking)
{
TRACKMOUSEEVENT tme;
tme.cbSize =
sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack =
this->m_hWnd;
  if (::_TrackMouseEvent(&tme))
{
m_bMouseTracking = TRUE;
}
 }

CEdit::OnMouseMove(nFlags, point);
}

No comments: