In this post, we are going to discuss all about event handling in SDL. But before moving ahead, I have some more things for you. In the previous post, we used SDL_WINDOW_SHOWN in SDL_CreateWindow() method for forcing the window to be shown. We can have 0 or NULL here. But then, if there are other programs running, it might be possible that the window formed, is not shown and then, we have to click the application from below (i.e taskbar) to bring it on screen. Of course, we can have full screen, minimized screen and etc. All the window flags are here.
Similarly, there are some additional settings for renderer or you can say that there are some renderer flags as well which are listed here. The renderer flag, SDL_RENDERER_PRESENTVSYNC is something to understand. It limits the frame rates of the application to that of the refresh rate of the monitor which is usually, 60.
Now, you might be wondering that how is this possible to have flags: SDL_WINDOW_SHOWN and SDL_WINDOW_MAXIMIZED as parameters for the SDL_CreateWindow() method. It is possible by putting '|' in between the two as mentioned below:
Now, lets see what is event handling. It is just a way to catch the events and then, respond accordingly. Basically, we have to poll through all the events. Of course, there are way too much with event handling and there are many kinds of events. But we will not be facing all of them! At least, for now.
If you put all the codes as in the previous post in an infinite while loop, it will not respond to your action. It will not respond to that click on the cross button at the top left of the window! How can you close this now?
Fortunately, we have the stop button with almost every IDE. Or just have Ctrl+Shift+Delete to open up the task manager and then, end that task from here. But you may not expect the same from the user. It is not neat and comfortable! Why is there a cross on the top left of the window if you have to close it like this? We have to handle every key pressed down, every mouse click, every.....
Man! I am talking too much! Lets get it done with the codes below. It is almost the same as that of the previous post with some exceptions. It is now, in a while loop and has no SDL_Delay() method. The while loop contains another while loop which processes the events through the object called SDL_Event.
The concept of the events in SDL is that, there is a line of awaiting events which gets polled through the SDL_PollEvent() method. We have to poll through all the events till the number of events gets to zero (of course). Then, from the SDL_Event object, we have to get to that event's root. First comes the type of the event and for each type, there are further specializations and so on until we get to that actual event. For now, it is too simple. Now, the cross button at the top left corner of the window is properly responded. Pressing any key will change the color of the screen.
And as always, Happy Coding!