我可以在 SDL 窗口外跟踪我的鼠标 pos 吗?

Can i track my mouse pos outside a SDL window?

本文关键字:鼠标 pos 我的 跟踪 SDL 窗口 我可以      更新时间:2023-10-16

我用 SDL 构建了一个时钟,它是一个没有边框的窗口。 现在我仍然希望能够在屏幕上移动我的时钟,所以我写了一个函数来移动它。基本上,它等待鼠标按下输入,然后计算移动的距离,直到您释放鼠标。然后它移动窗口。问题是它只在我的时钟窗口中获得鼠标pos,所以如果我单击左上角然后滑动到时钟窗口的右下角,我几乎可以移动它。

sPos moveClock(int event){
if(event==-1&&mPos.x==0&&mPos.y==0){
mPos = setPos(gvMousePos.x,gvMousePos.y);
cout << "down" << endl;
}
if(event==-65){
mPos = setPos(gvMousePos.x-mPos.x,gvMousePos.y-mPos.y);
cout << "up" << endl;
sPos temPos = mPos;
mPos = setPos(0,0);
return temPos;
}
return setPos(0,0);
}

我希望能够在屏幕上的任何位置移动我的时钟,所以我需要一种方法来让我的鼠标即使在窗外。或者一种在鼠标按下时计算距离的方法,即使我移动到 SDL 创建的窗口之外。

SDL_CaptureMouse()

brief捕获鼠标,以跟踪 SDL 窗口外的输入。

启用param是否启用捕获

捕获使应用能够全局获取鼠标事件,而不是 就在你的窗户里。并非所有视频定位条件都支持此功能。启用捕获后,当前窗口将获取所有鼠标事件, 但与相对模式不同的是,不会对光标进行任何更改,而是 不拘泥于你的窗户。

此函数还可能拒绝鼠标输入到其他窗口 - 这两个窗口 您的应用程序和系统上的其他应用程序 - 因此您应该使用它 功能谨慎,并且小爆发。例如,您可能希望 在用户拖动内容时跟踪鼠标,直到用户 释放鼠标按钮。不建议您捕获鼠标 长时间,例如应用运行的整个时间。

捕获时,鼠标事件仍报告相对于 当前(前景(窗口,但这些坐标可能位于 窗口的边界(包括负值(。捕获只是 允许前景窗口。如果窗口在 捕获时,捕获将自动禁用。

启用捕获时,当前窗口将具有SDL_WINDOW_MOUSE_CAPTURE标志集。

成功时return0,如果不支持,则为 -1。

extern DECLSPEC int SDLCALL SDL_CaptureMouse(SDL_bool enabled);

SDL_GetGlobalMouseState()可能是你需要的:

/**
* Get the current state of the mouse in relation to the desktop.
*
* This works similarly to SDL_GetMouseState(), but the coordinates will be
* reported relative to the top-left of the desktop. This can be useful if you
* need to track the mouse outside of a specific window and SDL_CaptureMouse()
* doesn't fit your needs. For example, it could be useful if you need to
* track the mouse while dragging a window, where coordinates relative to a
* window might not be in sync at all times.
*
* Note: SDL_GetMouseState() returns the mouse position as SDL understands it
* from the last pump of the event queue. This function, however, queries the
* OS for the current mouse position, and as such, might be a slightly less
* efficient function. Unless you know what you're doing and have a good
* reason to use this function, you probably want SDL_GetMouseState() instead.
*
* param x filled in with the current X coord relative to the desktop; can be
*          NULL
* param y filled in with the current Y coord relative to the desktop; can be
*          NULL
* returns the current button state as a bitmask which can be tested using
*          the SDL_BUTTON(X) macros.
*
* since This function is available since SDL 2.0.4.
*
* sa SDL_CaptureMouse
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetGlobalMouseState(int *x, int *y);

它用全局鼠标位置填充 x 和 y,并返回当前鼠标按钮状态。