Handling Unsupported Display Modes

What happens if a player has a monitor that doesn't support the display mode our game wants to use?

SDL provides several layers of protection against this scenario. Let's look at how to handle unsupported display modes safely:

Using 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

Error Handling

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.

Display Modes

Learn how to manage screen resolutions and refresh rates in SDL games using display modes.

Questions & Answers

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

Scaling Retro Games
If I'm making a retro-style game that uses a low resolution, how can I make it look good on modern high-resolution displays?
Display Mode Safety Timer
How can we implement a system that reverts to the previous display mode after a timer if the user doesn't confirm the changes?
Display Settings and Game Restart
Why do some games require a restart after changing display settings while others can change them instantly?
Saving Fullscreen Preferences
How can I save the player's preferred fullscreen mode and restore it the next time they launch the game?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant