For personal use, I'm coding an additional layer on SDL2, which includes an event manager. It correctly detects every type of event, except SDL_WINDOWEVENT_CLOSE
. After trying to debug my code, I realized that SDL2 actually never fires that event on my device... So there's no problem when I have only 1 window (because SDL_QUIT
is thrown instead), but when I have several windows I just can't detect when a window closing is requested, and I have to ctrl+C my program from the shell to have SDL_QUIT
fired manually.
Here is a minimal working example :
#include <stdio.h>
#include <SDL2/SDL.h>
int main(void){
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window *window = SDL_CreateWindow("A title", 0, 0, 720, 480, 0);
SDL_Window *window2 = SDL_CreateWindow("Another title", 0, 500, 720, 480, 0);
SDL_Event event;
_Bool running = 1;
while (running){
while (SDL_PollEvent(&event)){
if (event.type == SDL_WINDOWEVENT_CLOSE){
printf("Close event !\n");
running = 0;
}
if (event.type == SDL_QUIT){
printf("Quit event !\n");
running = 0;
}
}
}
SDL_DestroyWindow(window);
SDL_DestroyWindow(window2);
SDL_Quit();
return 0;
}
On my device nothing happens when I try to close a window (I am under Ubuntu 24.04 LTS, if this may help)
Am I missing something ?
The event.type
will not be SDL_WINDOWEVENT_CLOSE
but SDL_WINDOWEVENT
. That event type then has a lot of events defined for it, like SDL_WINDOWEVENT_CLOSE
.
Your loop could therefore look like this instead:
#include <SDL2/SDL.h>
#include <stdio.h>
int main() {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindow("A title", 0, 0, 720, 480, 0);
SDL_Window* window2 = SDL_CreateWindow("Another title", 0, 500, 720, 480, 0);
SDL_Event event;
_Bool running = 1;
while(running) {
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT: {
puts("SDL_QUIT");
running = 0;
break;
}
case SDL_WINDOWEVENT: {
SDL_WindowEvent* we = (SDL_WindowEvent*)&event;
switch(we->event) {
case SDL_WINDOWEVENT_CLOSE: {
puts("SDL_WINDOWEVENT_CLOSE");
running = 0;
break;
}
}
break;
}
}
}
}
SDL_DestroyWindow(window);
SDL_DestroyWindow(window2);
SDL_Quit();
}