
Introduction
Whenever MFC applications are written and, above all whenever we write controls, it often
happens that we want to find a way to know when the mouse enters on our control window
and when it leaves. Unfortunately, as we know, Windows does not support these kind of events.
Using the code
The idea standing behind this source is very simple, just handle the WM_MOUSEMOVE
message and
capture the mouse input with the SetCapture
function. So you will have to test
if the pointer is actually on your window. If not you have to release the mouse (ReleaseCapture
).
In order to have the OnMouseEnter
& OnMouseLeave
functions you have to keep a BOOL
updated
with TRUE
whether the pointer is on the Window and FALSE
when it isn't. When you try to turn on
the BOOL
, if it's not already TRUE
you will have a MouseEnter
. While, every time you call a ReleaseCapture
you will have a MouseLeave
.
void CMyWnd::OnMouseMove(UINT nFlags, CPoint point)
{
SetCapture();
CRect wndRect;
GetWndRect(&wndRect);
ScreenToClient(&wndRect);
if (wndRect.PtInRect(point))
{
if (m_PointerOnWnd != TRUE)
{
OnMouseEnter();
m_PointerOnWnd = TRUE;
}
}
else
{
ReleaseCapture();
m_PointerOnWnd = FALSE;
}
CWnd::OnMouseMove(nFlags, point);
}
There's no problem even if the mouse is on the window when the application starts,
because in this case
Windows will automatically send a WM_MOUSEMOVE
event.
That's all folks