Get current cursor position

C++Winapi

C++ Problem Overview


I want to get the current mouse position of the window, and assign it to 2 variables x and y (co-ordinates relative to the window, not to the screen as a whole).

I'm using Win32 and C++.

And a quick bonus question: how would you go about hiding the cursor/unhiding it?

C++ Solutions


Solution 1 - C++

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

Solution 2 - C++

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionI Phantasm IView Question on Stackoverflow
Solution 1 - C++David HeffernanView Answer on Stackoverflow
Solution 2 - C++Mike KwanView Answer on Stackoverflow