Here's how to implement a safety timer for display mode changes:
#include <SDL.h>
#include <iostream>
class DisplayModeGuard {
SDL_Window* Window;
SDL_DisplayMode PreviousMode;
Uint32 StartTime;
Uint32 TimeoutMs;
bool Confirmed{false};
public:
DisplayModeGuard(
SDL_Window* Window,
Uint32 TimeoutMs
) : Window{Window}, TimeoutMs{TimeoutMs} {
// Store current mode before changes
SDL_GetWindowDisplayMode(
Window, &PreviousMode);
StartTime = SDL_GetTicks();
}
void Confirm() { Confirmed = true; }
bool HasExpired() const {
return !Confirmed && (SDL_GetTicks() -
StartTime >= TimeoutMs);
}
void RevertIfNeeded() {
if (HasExpired()) {
SDL_SetWindowDisplayMode(
Window, &PreviousMode);
}
}
~DisplayModeGuard() { RevertIfNeeded(); }
};
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* Window{SDL_CreateWindow(
"Display Mode Test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600, 0
)};
// Create guard with 15 second timeout
DisplayModeGuard Guard{Window, 15000};
// Try new display mode
SDL_DisplayMode NewMode{
0, 1920, 1080, 60, nullptr};
SDL_SetWindowDisplayMode(Window, &NewMode);
SDL_SetWindowFullscreen(
Window, SDL_WINDOW_FULLSCREEN);
std::cout << "Press Enter to confirm new display"
" mode or wait 15 seconds to revert\n";
// Simple event loop
bool Running{true};
while (Running) {
SDL_Event Event;
while (SDL_PollEvent(&Event)) {
if (Event.type == SDL_KEYDOWN &&
Event.key.keysym.sym == SDLK_RETURN) {
Guard.Confirm();
Running = false;
} else if (Event.type == SDL_QUIT) {
Running = false;
}
}
if (Guard.HasExpired()) { Running = false; }
SDL_Delay(16);
}
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
This implementation uses RAII (Resource Acquisition Is Initialization) to ensure the display mode reverts if not confirmed. The DisplayModeGuard
 class:
You could expand this system by adding a visual countdown or handling additional user input types.
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.