Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current cursor position

Tags:

c++

winapi

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?

like image 486
I Phantasm I Avatar asked Jun 21 '11 10:06

I Phantasm I


People also ask

How do I find my current cursor position?

To get the cursor position in JavaScript, we can use the MouseEvent client properties, that is the clientX Property and the clientY Property. To get the cursor position we will need to attach a mouse event to either a div on the page or to the whole page document itself.

How do I get the cursor position in HTML?

If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.

How do I get the cursor position in C++?

You get the cursor position by calling GetCursorPos . This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.


1 Answers

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.

like image 90
David Heffernan Avatar answered Oct 16 '22 12:10

David Heffernan