Here's a comprehensive solution for managing fullscreen preferences:
#include <iostream>
#include <fstream>
#include <SDL.h>
enum class FullscreenMode {
Windowed,
Fullscreen,
BorderlessFullscreen
};
struct WindowSettings {
FullscreenMode Mode{FullscreenMode::Windowed};
int Width{800};
int Height{600};
};
void SaveSettings(
const WindowSettings& Settings) {
std::ofstream File{"window_settings.cfg"};
if (File) {
File << static_cast<int>(Settings.Mode)
<< "\n"
<< Settings.Width << "\n"
<< Settings.Height;
}
}
WindowSettings LoadSettings() {
WindowSettings Settings;
std::ifstream File{"window_settings.cfg"};
if (File) {
int Mode;
File >> Mode;
Settings.Mode = static_cast<FullscreenMode>(
Mode);
File >> Settings.Width >> Settings.Height;
}
return Settings;
}
Uint32 GetSDLFullscreenFlags(FullscreenMode Mode) {
switch (Mode) {
case FullscreenMode::Fullscreen:
return SDL_WINDOW_FULLSCREEN;
case FullscreenMode::BorderlessFullscreen:
return SDL_WINDOW_FULLSCREEN_DESKTOP;
default:
return 0;
}
}
bool ApplyWindowSettings(
SDL_Window* Window,
const WindowSettings& Settings) {
// Store current display mode for fallback
SDL_DisplayMode CurrentMode;
SDL_GetWindowDisplayMode(
Window, &CurrentMode);
// Apply new size if windowed
if (Settings.Mode ==
FullscreenMode::Windowed) {
SDL_SetWindowSize(
Window,
Settings.Width,
Settings.Height
);
}
// Apply fullscreen mode
if (SDL_SetWindowFullscreen(
Window,
GetSDLFullscreenFlags(Settings.Mode)) < 0) {
// Revert on failure
SDL_SetWindowFullscreen(Window, 0);
SDL_SetWindowSize(
Window, CurrentMode.w, CurrentMode.h);
return false;
}
return true;
}
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
// Load saved settings
WindowSettings Settings{LoadSettings()};
// Create initial window
SDL_Window* Window{
SDL_CreateWindow(
"Game",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
Settings.Width,
Settings.Height,
GetSDLFullscreenFlags(Settings.Mode)
)};
// Game loop would go here...
// Save settings before exit
SaveSettings(Settings);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
This implementation:
For better error handling, you might want to add:
Remember to handle the window size appropriately when switching between modes - borderless fullscreen will use the desktop resolution, while exclusive fullscreen uses the configured resolution.
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.