SDL
SDL copied to clipboard
SDL_WaitEvent() don't seems to empty the event buffer
Hi everyone
I don't know is this issue have been sent before, but I find something wrong when trying to open a new window after the closure of a precedent one. I use the SDL2 with Code::Blocks running Lubuntu 18.04 (32 bits) and 22.04 (64 bits).
When I close the first window (Q or ESC key), SDL_WaitEvent() don't seems to empty the event buffer and the second window closes immediately on the same key...
Let's see the code:
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
int main()
{
cerr<<"Start Problem"<<endl;
SDL_Window *WindowPtr=nullptr; //window ptr
SDL_Event event; //an event
int waitEventBool = 1; //flag to stay in the event loop
//Simple init SDL2
if(SDL_Init(SDL_INIT_VIDEO)==-1)
{
cerr<<"SDL 2 initialization failure... "<<SDL_GetError()<<endl;
exit(EXIT_FAILURE);
}
WindowPtr=SDL_CreateWindow("First window; Q or ESC key to exit", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 360, SDL_WINDOW_SHOWN);
if(WindowPtr==nullptr)
{
cerr<<"First window creation failure..."<<SDL_GetError()<<endl;
exit(EXIT_FAILURE);
}
waitEventBool = 1;
while(waitEventBool)
{
SDL_WaitEvent(&event); //stop and wait an event
switch(event.type)
{
case SDL_QUIT: //Quit event
waitEventBool=0;
break;
case SDL_KEYDOWN: //key press
switch(event.key.keysym.sym) //which key ?
{
case SDLK_ESCAPE:
cout<<"Exit #1 ESC key"<<endl;
waitEventBool=0;
break;
case SDLK_q:
cout<<"Exit #1 on Q key"<<endl;
waitEventBool=0;
break;
default:
break;
}
break;
}
}
//Destroy the first window
SDL_DestroyWindow(WindowPtr);
WindowPtr=SDL_CreateWindow("Second window; Q or ESC key to exit", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 400, 240, SDL_WINDOW_SHOWN);
if(WindowPtr==nullptr)
{
cerr<<"Second window creation failure..."<<SDL_GetError()<<endl;
exit(EXIT_FAILURE);
}
waitEventBool = 1;
while(waitEventBool)
{
SDL_WaitEvent(&event); //stop and wait an event
switch(event.type)
{
case SDL_QUIT: //Quit event
waitEventBool=0;
break;
case SDL_KEYDOWN: //key press
switch(event.key.keysym.sym) //which key ?
{
case SDLK_ESCAPE:
cout<<"Exit #2 ESC key"<<endl;
waitEventBool=0;
break;
case SDLK_q:
cout<<"Exit #2 on Q key"<<endl;
waitEventBool=0;
break;
default:
break;
}
break;
}
}
//Destroy the second window
SDL_DestroyWindow(WindowPtr);
//Quit SDL
SDL_Quit();
cerr<<"End Problem"<<endl;
return EXIT_SUCCESS;
}
I added the following lines before the second event loop (line 66) and it seems to solve the problem... So why SDL_WaitEvent() maintains the key pressed in the event buffer ?
SDL_PumpEvents();
SDL_FlushEvent(SDL_KEYDOWN);
I thank you if you can tell me where I'm wrong.
Francis