SDL provides several layers of protection against this scenario. Let's look at how to handle unsupported display modes safely:
SDL_GetClosestDisplayMode()
The safest approach is to always use SDL_GetClosestDisplayMode()
before setting a display mode. This function will find the closest supported mode:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
// The mode we want to use
SDL_DisplayMode Desired{
0, 1920, 1080, 144, nullptr
};
SDL_DisplayMode Closest;
// Find the closest supported mode
if (SDL_GetClosestDisplayMode(
0, &Desired, &Closest)) {
std::cout << "Found mode: "
<< Closest.w << "x" << Closest.h << " @ "
<< Closest.refresh_rate << "Hz\n";
} else {
std::cout << "No compatible mode found\n";
}
SDL_Quit();
return 0;
}
Found mode: 1920x1080 @ 144Hz
If we try to set an unsupported mode directly, SDL will return an error:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* Window{SDL_CreateWindow(
"Window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600, 0
)};
// Try to set an unsupported mode
SDL_DisplayMode Unsupported{
0, 99999, 99999, 0, nullptr
};
if (SDL_SetWindowDisplayMode(
Window, &Unsupported
) < 0) {
std::cout << "Error: " << SDL_GetError();
}
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
The best practice is to always validate display modes before attempting to use them, and have a fallback mode ready in case the preferred mode isn't available.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to manage screen resolutions and refresh rates in SDL games using display modes.