SDL2 multiple windows

Hello! I have created 2 windows, I want to close the window under the heading “Window”, but it won’t close. Why is it so?

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>

int main(){
    SDL_Window *window=SDL_CreateWindow("Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 800, SDL_WINDOW_OPENGL);
    SDL_Window *window1=SDL_CreateWindow("Window1", 0, 0, 800, 800, SDL_WINDOW_OPENGL);
    SDL_Event event;

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

    SDL_GLContext glContext=SDL_GL_CreateContext(window);

    SDL_GL_SetSwapInterval(SDL_FALSE);

    SDL_GL_MakeCurrent(window, glContext);

    while(window!=NULL){
        while(SDL_PollEvent(&event)){
            if(event.type==SDL_QUIT)
                window1=NULL;
        }

        glClearColor(0, 0, 0, 0);
        glClear(GL_COLOR_BUFFER_BIT);

        SDL_GL_SwapWindow(window);
    }
}

You only get an SDL_QUIT event when all windows have closed (or rather, when the last window fires an SDL_WINDOWEVENT_CLOSE event, which is a little confusing but works in the usual case)

The confusing part: the close event doesn’t actually close the window; it tells you the user clicked the button on the titlebar, but you are free to ignore it (that’s the confusing part, because you can ignore this and still get an SDL_QUIT event).

So try this instead:

while(SDL_PollEvent(&event)){
    if((event.type==SDL_WINDOWEVENT) && (event.window.event == SDL_WINDOWEVENT_CLOSE)) {
        // only close the window if we haven't already and this event was from this window (and not the other!).
        if ((window1 != NULL) && (SDL_GetWindowFromID(event.window.id) == window1)) {
            SDL_DestroyWindow(window1);
            window1=NULL;
        }
    }
}
1 Like