C++ 获取当前光标位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6423729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current cursor position
提问by I Phantasm I
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).
我想获取窗口的当前鼠标位置,并将其分配给 2 个变量x
和y
(相对于窗口的坐标,而不是整个屏幕的坐标)。
I'm using Win32 and C++.
我正在使用 Win32 和 C++。
And a quick bonus question: how would you go about hiding the cursor/unhiding it?
还有一个快速的奖励问题:您将如何隐藏/取消隐藏光标?
回答by David Heffernan
You get the cursor position by calling GetCursorPos
.
您可以通过调用获取光标位置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.
这将返回相对于屏幕坐标的光标位置。调用ScreenToClient
以映射到窗口坐标。
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
。
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.
您必须确保每次隐藏光标的调用都与再次显示光标的调用相匹配。
回答by Mike Kwan
GetCursorPos()will return to you the x/y if you pass in a pointer to a POINT structure.
如果您传入指向 POINT 结构的指针,GetCursorPos()将返回给您 x/y。
Hiding the cursor can be done with ShowCursor().
可以使用ShowCursor()来隐藏光标。