Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MouseLeave and MouseEnter functions

0.00/5 (No votes)
22 Dec 2002 1  
A simple way to implement MouseLeave & Mouse Enter functions

Sample Image - MouseEnterLeave.gif

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();               //  Capture the mouse input

  CRect wndRect;
  GetWndRect(&wndRect);
  ScreenToClient(&wndRect);

  if (wndRect.PtInRect(point))	
  {  // Test if the pointer is on the window

    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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here