Handling the Window Close Event in SDL2

How do I make the window close properly when I click the 'X' button?

Clicking the standard window close button ('X' on Windows/Linux, red circle on macOS) doesn't automatically close your SDL application. Instead, the operating system sends a specific signal to your application indicating the user wants to quit. SDL translates this signal into an event of type SDL_QUIT.

To make your window close properly, you need to modify your main application loop to:

  1. Check for pending events.
  2. Specifically look for an event of type SDL_QUIT.
  3. If SDL_QUIT is detected, signal your main loop to stop running.

Implementing the Event Loop

The standard way to do this is using SDL_PollEvent(). This function checks SDL's internal event queue (which is populated by calls to SDL_PumpEvents(), often implicitly by SDL_PollEvent itself) for the next pending event. If an event exists, SDL_PollEvent() fills an SDL_Event structure with the event details and returns 1 (true). If no events are pending, it returns 0 (false).

We use a while loop with SDL_PollEvent() to process all events that might have occurred since the last frame, and a boolean flag (e.g., running) to control the main application loop.

Here's how you can modify the main.cpp from the lesson to handle the close event:

// main.cpp
#include <SDL.h>
#include "Window.h"

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_VIDEO);
  Window GameWindow; // Creates the window via constructor

  bool running = true;  // Add a flag to control the loop
  SDL_Event event;      // Structure to hold event info

  // Replace while(true) with while(running)
  while (running) {  // Loop continues as long as running is true

    // Process all pending events this frame
    while (SDL_PollEvent(&event)) {  // Check for events
      // Check if the event is the quit signal
      if (event.type == SDL_QUIT) { 
        running = false; // Signal the main loop to stop <h>
      }
      // We could check for other events here (keyboard, mouse)
    }

    // If we were rendering or updating game state,
    // it would happen here, outside the event polling loop
    // but inside the main 'while(running)' loop.

    // SDL_PumpEvents() is not strictly needed here, as
    // SDL_PollEvent() handles event pumping internally.
  }

  // Destructor of GameWindow runs here, calling SDL_DestroyWindow

  SDL_Quit(); // Clean up SDL subsystems
  return 0;
}

With this structure:

  • The while(running) loop keeps the application alive.
  • SDL_PollEvent() checks for user actions or system events.
  • When the 'X' button is clicked, an SDL_QUIT event is generated.
  • The if (event.type == SDL_QUIT) condition becomes true.
  • running is set to false.
  • The while(running) loop condition fails on the next iteration, and the loop terminates.
  • The program proceeds to SDL_Quit() and exits gracefully.

Event handling is a fundamental part of SDL applications, and we will cover it much more thoroughly in the upcoming lessons, including handling keyboard and mouse input.

Creating a Window

Learn how to create and customize windows, covering initialization, window management, and rendering

Questions & Answers

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

Purpose of SDL_Quit() in SDL2
Why do we need to call SDL_Quit()? What happens if we forget?
Understanding Screen Coordinates and Pixels in SDL2
What exactly is a "screen coordinate"? Is it always the same as a pixel?
How Window Position is Determined when using SDL_WINDOWPOS_UNDEFINED
How does does SDL decide where to actually place the window when using SDL_WINDOWPOS_UNDEFINED?
Understanding SDL_PumpEvents() and the Event Loop
What does SDL_PumpEvents() actually do? Why is it in an infinite loop?
The Rule of Three/Five and SDL Resource Management
What is the "Rule of Three" and why did deleting the copy operations satisfy it here? What about the Rule of Five?
Using Raw vs. Smart Pointers for SDL Resources
Is SDL_Window* a raw pointer? Should I be using smart pointers like std::unique_ptr?
Purpose of argc and argv in SDL Applications
What are argc/argv in main for? Do I need them here?
How to Handle Window Close Events in SDL
How can I make my SDL window respond to close events, such as clicking the close button?
Using Multiple Windows in SDL
Can I create and manage multiple windows in SDL, and if so, how?
Adjusting Window Size Dynamically in SDL
How can I adjust the size of an SDL window dynamically during runtime?
Improving SDL Window Performance
What are some tips to improve the performance of an SDL window?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant