To retrieve the current position of the mouse cursor in SDL, you need to handle SDL_MOUSEMOTION
 events.
When the user moves the mouse, SDL generates an event of type SDL_MOUSEMOTION
. This event contains the new x
and y
coordinates of the mouse cursor. You can access these coordinates using the motion
member of the SDL_Event
 structure.
Here’s a basic example of how to retrieve and print the mouse position:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "SDL_Init Error: "
<< SDL_GetError() << '\n';
return 1;
}
SDL_Window* window = SDL_CreateWindow(
"Mouse Position",
100, 100, 640, 480,
SDL_WINDOW_SHOWN
);
if (window == nullptr) {
std::cerr << "SDL_CreateWindow Error: "
<< SDL_GetError() << '\n';
SDL_Quit();
return 1;
}
SDL_Event event;
bool running = true;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
} else if (event.type == SDL_MOUSEMOTION) {
int x = event.motion.x;
int y = event.motion.y;
std::cout << "Mouse Position - x: "
<< x << ", y: " << y << '\n';
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Mouse Position - x: 123, y: 456
Mouse Position - x: 130, y: 460
Mouse Position - x: 140, y: 470
In this example:
SDL_Init(SDL_INIT_VIDEO)
initializes the SDL video subsystem.SDL_CreateWindow()
creates a window where the mouse events will be captured.SDL_PollEvent()
function polls for currently pending events. If an event is detected, it updates the event
object.SDL_MOUSEMOTION
and then retrieve the mouse coordinates from event.motion.x
and event.motion.y
.These coordinates are relative to the window's top-left corner.
If you need the mouse position relative to the screen, you can use SDL_GetMouseState()
instead, which returns the current state of the mouse and fills the provided x
and y
pointers with the mouse cursor’s screen coordinates.
Here’s an example using SDL_GetMouseState()
:
int x, y;
SDL_GetMouseState(&x, &y);
std::cout << "Mouse Position - x: " << x
<< ", y: " << y << '\n';
This code retrieves the current mouse position relative to the entire screen, not just the window. Using these methods, you can accurately track and use the mouse position in your SDLÂ applications.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to detect and handle mouse input events in SDL, including mouse motion, button clicks, and window entry/exit.