Centering Window on Specific Display
How can I move an SDL window to the centre of a specific display?
To move an SDL window to the center of a specific display, you can use the following steps:
- Retrieve the display bounds: Use
SDL_GetDisplayBounds
to get the dimensions of the specific display. - Calculate the centered position: Compute the
(x, y)
coordinates to center the window on the display. - Move the window: Use
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.
1. 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).- Returns a rectangle (
SDL_Rect
) with the display's dimensions and position.
2. SDL_GetWindowSize()
Retrieves the current width and height of the SDL window.
3. Center calculation
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;
4. SDL_SetWindowPosition()
Moves the window to the calculated (x, y)
coordinates.
5. Notes
- Make sure the
displayIndex
you use is valid. UseSDL_GetNumVideoDisplays()
to find the number of available displays. - If the window is resizable, ensure the window's size is finalized before centering it.
Video Displays
Learn how to handle multiple monitors in SDL, including creating windows on specific displays.