To move an SDL window to the center of a specific display, you can use the following steps:
SDL_GetDisplayBounds
to get the dimensions of the specific display.(x, y)
coordinates to center the window on the display.SDL_SetWindowPosition
to reposition the window.Here’s an example:
#include <SDL.h>
#include <iostream>
void CenterWindowOnDisplay(
SDL_Window* window, int displayIndex
) {
if (!window) {
std::cerr << "Window is null!\n";
return;
}
SDL_Rect displayBounds;
if (SDL_GetDisplayBounds(
displayIndex, &displayBounds
) != 0) {
std::cerr << "Failed to get display "
"bounds: " << SDL_GetError() << "\n";
return;
}
int windowWidth, windowHeight;
SDL_GetWindowSize(
window, &windowWidth, &windowHeight);
int centeredX = displayBounds.x + (
displayBounds.w - windowWidth) / 2;
int centeredY = displayBounds.y + (
displayBounds.h - windowHeight) / 2;
SDL_SetWindowPosition(
window, centeredX, centeredY);
}
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(
"Centered Window",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600,
SDL_WINDOW_SHOWN
);
if (!window) {
std::cerr << "SDL_CreateWindow Error: "
<< SDL_GetError() << "\n";
SDL_Quit();
return 1;
}
// Center the window on display 1 (change
// index as needed)
CenterWindowOnDisplay(window, 1);
// Wait 3 seconds to see the window
SDL_Delay(3000);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Let’s review the key components.
SDL_GetDisplayBounds()
Fetches the position and size of the specified display.
displayIndex
: Index of the display you want to use (e.g., 0
for the primary display).SDL_Rect
) with the display's dimensions and position.SDL_GetWindowSize()
Retrieves the current width and height of the SDLÂ window.
Calculating how to position a window to center it within the display bounds uses the following arithmetic:
int centeredX = displayBounds.x + (
displayBounds.w - windowWidth) / 2;
int centeredY = displayBounds.y + (
displayBounds.h - windowHeight) / 2;
SDL_SetWindowPosition()
Moves the window to the calculated (x, y)
 coordinates.
displayIndex
you use is valid. Use SDL_GetNumVideoDisplays()
to find the number of available displays.Answers to questions are automatically generated and may not have been reviewed.
Learn how to handle multiple monitors in SDL, including creating windows on specific displays.