Cant get SDL2 event's from window

I my trying to learn SDL in C++ . I have simple program which will display a image . but When I try to close window by clicking close button on the window nothing happens.

here is my code:-
#include <SDL2/SDL.h>
int main(int argc,char **argv)
{
static int k =0;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *w;
w = SDL_CreateWindow(“SDL VS Works”,300,300,400,500,SDL_WINDOW_OPENGL);

    SDL_Renderer *render = SDL_CreateRenderer(w,-1,SDL_RENDERER_ACCELERATED);

    SDL_Surface *tux  = SDL_LoadBMP("res/tux.bmp");

    SDL_Texture *texture = SDL_CreateTextureFromSurface(render,tux);
    SDL_FreeSurface(tux);
    SDL_ShowWindow(w);
    SDL_Event event;

    while(1)
    {
        k++;
        printf("Running and loop %d\'th\n",k);
        SDL_PollEvent(&event);
        if(event.type == SDL_QUIT)
        {
            printf("closing \n");
            goto sos;
        }
        SDL_RenderCopy(render,texture,0,0);
        SDL_RenderPresent(render);
        SDL_Delay(1000);

    }


sos:
    SDL_DestroyWindow(w);
    SDL_DestroyRenderer(render);
    SDL_DestroyTexture(texture);

    SDL_Quit();
}

some people so stackoverflow say that it worked for them. It also works 00.1% sometime and I don’t have any Idea why that happens

I am using g++ 7.3 on Arch Linux.

Try putting PollEvent inside while loop, like here: https://wiki.libsdl.org/SDL_PollEvent

You didn’t actually check if there was an event available or not. My theory is that you have a bunch of events like mouse movement and SDL_Quit is somewhere in the back of line.

So handle all events first, sleep after.

If that doesn’t help, print every received event type.

1 Like