63

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?

Johan
  • 74,508
  • 24
  • 191
  • 319
I Phantasm I
  • 1,651
  • 5
  • 22
  • 28

2 Answers2

135

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 5
    GetCursorPos retrieves screen coordinates while the question asked explicitly for window coordinates. `ScreenToClient`/`MapWindowPoints` is missing from your answer. – Sertac Akyuz Jun 21 '11 at 11:42
  • What happens if the hiding and showing calls are not matched? Does it leave the cursor hidden even after the windows/program is closed? – Banderi Jul 28 '15 at 16:32
  • If you're working with OpenGL like I was when I found this, you might find [GetClientRect(HWND, LPRECT)](https://msdn.microsoft.com/en-us/library/ms633503(v=vs.85).aspx) as useful as I found this when you are flipping the mouse y coord. Cheers – coolhandle01 Apr 05 '17 at 20:13
17

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().

Mike Kwan
  • 24,123
  • 12
  • 63
  • 96