Yes, SDL provides functions to get the mouse cursor's position relative to the global screen/desktop coordinates, rather than just relative to a specific application window.
SDL_GetGlobalMouseState()
The primary function for this is SDL_GetGlobalMouseState()
. It retrieves the current state of the mouse, including its position on the screen.
#include <SDL.h>
#include <iostream>
int main(int argc, char** argv) {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "SDL could not initialize! SDL_Error: "
<< SDL_GetError() << '\n';
return 1;
}
// No window creation needed just to get global state
int mouseX, mouseY;
Uint32 mouseButtonState = SDL_GetGlobalMouseState(
&mouseX, &mouseY
);
std::cout << "Global Mouse Position - x: " << mouseX
<< ", y: " << mouseY << '\n';
if (mouseButtonState & SDL_BUTTON(SDL_BUTTON_LEFT)) {
std::cout << "Left mouse button is pressed globally.\n";
}
SDL_Quit();
return 0;
}
Global Mouse Position - x: 1024, y: 512
Left mouse button is pressed globally.
This function takes pointers to two integers (int* x
, int* y
) which it fills with the current global x and y coordinates of the mouse cursor. It also returns a bitmask representing the state of the mouse buttons globally (useful if you need to know button states without relying on window focus).
SDL_GetMouseState()
(Relative to Focused Window)For comparison, remember that SDL_GetMouseState()
provides the mouse position relative to the window that currently has mouse focus. If no window in your application has focus, the coordinates returned by SDL_GetMouseState()
might not be meaningful or could be relative to the desktop.
// Inside your main loop or where you have a window context
int windowMouseX, windowMouseY;
SDL_GetMouseState(&windowMouseX, &windowMouseY);
// windowMouseX, windowMouseY are relative to the focused window
Getting global coordinates is less common in game development than window-relative coordinates, but it can be useful for:
For most in-game interactions (clicking buttons, selecting units, aiming), you'll typically use the window-relative coordinates provided by mouse events (event.motion.x
, event.button.x
) or SDL_GetMouseState()
.
Answers to questions are automatically generated and may not have been reviewed.
Discover how to process mouse input, including position tracking and button presses