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.
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';
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);
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.
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.