Creating a Window

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?

Abstract art representing computer programming

To make your SDL window respond to close events, you need to modify your event handling loop to detect when the SDL_QUIT event is triggered, which occurs when the window's close button is clicked. Here's how you can incorporate this into your code:

#include <SDL.h>
#include "Window.h"

int main(int argc, char** argv) {
  Window GameWindow;
  SDL_Event event;
  bool running = true;

  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        running = false; 
      }
    }
    GameWindow.RenderFrame();
  }

  SDL_Quit();
  return 0;
}

This modification introduces a boolean flag running that controls the main loop. The loop continues as long as running is true, but sets running to false when an SDL_QUIT event is detected, effectively closing the window.

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

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 40 Lessons
  • 100+ Code Samples
  • 91% 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