Building SDL2 from Source (GCC and Make)

Creating a Fullscreen Window in SDL2

How can I create a fullscreen window in SDL2?

Vector illustration representing computer programming

To create a fullscreen window in SDL2, you can use the SDL_WINDOW_FULLSCREEN flag when creating the window. Here's an example of how to create a fullscreen window:

#include <SDL.h>

int main(int argc, char* argv[]) {
  SDL_Init(SDL_INIT_VIDEO);

  SDL_Window* window{SDL_CreateWindow(
    "Fullscreen Window",
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP
  )};

  // Rendering and event handling code here
  // ...

  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}

In this example, we pass the SDL_WINDOW_FULLSCREEN_DESKTOP flag as the last argument to SDL_CreateWindow. This flag tells SDL2 to create a fullscreen window that covers the entire desktop.

Note that we set the width and height parameters to 0 since the window will automatically cover the entire screen.

If you want to toggle between fullscreen and windowed mode dynamically, you can use the SDL_SetWindowFullscreen function:

// Toggle fullscreen mode
if (SDL_GetWindowFlags(window)
  & SDL_WINDOW_FULLSCREEN_DESKTOP) {
  // Exit fullscreen
  SDL_SetWindowFullscreen(window, 0);
} else {
  // Enter fullscreen
  SDL_SetWindowFullscreen(window,
    SDL_WINDOW_FULLSCREEN_DESKTOP);
}

This code snippet checks the current window flags using SDL_GetWindowFlags to determine if the window is currently in fullscreen mode. If it is, it exits fullscreen mode by passing 0 to SDL_SetWindowFullscreen. Otherwise, it enters fullscreen mode by passing the SDL_WINDOW_FULLSCREEN_DESKTOP flag.

Remember to handle the necessary events, such as the SDL_KEYDOWN event, to trigger the fullscreen toggle based on user input.

Answers to questions are automatically generated and may not have been reviewed.

3D art representing computer programming
Part of the course:

Building Minesweeper with C++ and SDL2

Apply what we learned to build an interactive, portfolio-ready capstone project using C++ and the SDL2 library

Free, unlimited access

This course includes:

  • 37 Lessons
  • 100+ Code Samples
  • 92% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved