Check if mouse is over a window.

Today I was looking for a function to check if my mouse cursor was over my window to make sure mouse wheel behavior was only active when the cursor was right over the window receiving the message, but I didn’t find any on MSDN so here’s a nice snippet to check if the mouse cursor is over the window rectangle. It doesn’t check if the window is active or has the focus. Mouse coordinates can be passed in client or screen space, just make sure to set the inClientSpace parameter accordingly.

///////////////////////////////////////////////////////////////////
///
/// Checks if the mouse cursor is over the window.
///
/// @param hWnd        [IN] window handle
/// @param mx            [IN] x mouse coordinate
/// @param my            [IN] y mouse coordinate
/// @param inClientSpace [IN] indicates if we check coordinate in 
///                                        client or screen space.
///
/// @return true if the point is over the window area.
///
const bool IsMouseOverWindow(HWND hWnd, const int mx, const int my,
                          const bool inClientSpace /*= false */)
{
    RECT windowRect;
 
    // Get the window in screen space
    ::GetWindowRect( hWnd, &windowRect );
 
    if ( inClientSpace )
    {
        POINT offset;
        offset.x = offset.y = 0;
        ClientToScreen( hWnd, &offset );
 
        // Offset the window to client space
        windowRect.left -= offset.x;
        windowRect.top -= offset.y;
        // NOTE: left and top should now be 0, 0
        windowRect.right -= offset.x;
        windowRect.bottom -= offset.y;
    }
 
    // Test if mouse over window
    POINT cursorPos = { mx, my };
    return PtInRect( &windowRect, cursorPos );
}
This entry was posted in C++, Coding, Snippet and tagged , , . Bookmark the permalink.

One Response to Check if mouse is over a window.

  1. Digital Sagotharan says:

    nice.

Leave a Reply

Your email address will not be published. Required fields are marked *