Understanding SDL Display Indices

What are display indices, and how do they map to physical monitors?

SDL assigns a numerical index to each connected display. These indices start from 0 and increment for every additional monitor. Display indices are used throughout SDL's API to refer to specific monitors when querying their properties or creating windows.

Mapping to Physical Monitors

The display index corresponds to the monitor order reported by the operating system. For example, if you have three monitors connected, SDL_GetDisplayName(0) will return the name of the first monitor as recognized by the OS.

You can retrieve the total number of displays using SDL_GetNumVideoDisplays():

int numDisplays = SDL_GetNumVideoDisplays();
std::cout << "Number of displays: "
  << numDisplays << '\n';

Example Use Case

If you want to create a window on the second monitor, use display-specific macros like this:

SDL_CreateWindow("My Window",
                 SDL_WINDOWPOS_CENTERED_DISPLAY(1), 
                 SDL_WINDOWPOS_CENTERED_DISPLAY(1), 
                 800, 600, SDL_WINDOW_SHOWN);

How Indices Can Vary

  • If monitors are reconnected or the OS display order changes, the indices might not correspond to their previous mappings.
  • On multi-GPU setups, displays might appear in different orders depending on which GPU is active.

Display Index Pitfalls

Always verify the number of displays using SDL_GetNumVideoDisplays() to avoid referencing an out-of-bounds index. For example:

if (displayIndex >= SDL_GetNumVideoDisplays()) {
  std::cerr << "Invalid display index: "
    << displayIndex << '\n';
}

By understanding display indices, you can ensure your application works smoothly in multi-monitor environments.

Video Displays

Learn how to handle multiple monitors in SDL, including creating windows on specific displays.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Centering Window on Specific Display
How can I move an SDL window to the centre of a specific display?
Handling No Displays in SDL2
How do I handle the case where no displays are available?
SDL_WINDOWPOS_UNDEFINED Explained
What does the SDL_WINDOWPOS_UNDEFINED macro do, and why would I use it?
Handling Windows Exceeding Screen Boundaries
How do I handle cases where my window exceeds the screen boundaries on a specific monitor?
Specifying Display Index with SDL_CreateWindow()
Can I specify the display index when using SDL_CreateWindow()?
Forcing a Window to Appear on the Primary Monitor
How can I make my game window always appear on the primary monitor?
Displaying Windows on Different Monitors
How can I ensure windows are displayed on different monitors?
SDL_GetWindowDisplayIndex() for Multiple Displays
How does SDL_GetWindowDisplayIndex() work if the window spans multiple displays?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant