SDL2 provides an event system that allows you to handle various types of events, including keyboard and mouse events. Here's an example of how to handle multiple event types in an SDL2Â application:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window{SDL_CreateWindow(
"Event Handling",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_SHOWN
)};
SDL_Event event;
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
quit = true;
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym
== SDLK_ESCAPE) {
quit = true;
} else {
std::cout << "Key pressed: "
<< SDL_GetKeyName(
event.key.keysym.sym) << '\n';
}
break;
case SDL_MOUSEBUTTONDOWN:
std::cout << "Mouse button pressed: "
<< event.button.button << "\n";
break;
case SDL_MOUSEMOTION:
std::cout << "Mouse position: ("
<< event.motion.x << ", "
<< event.motion.y << ")\n";
break;
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
In this example, we use a switch
statement inside the event loop to handle different event types. The event.type
field determines the type of event that occurred.
SDL_QUIT
 event, we set the quit
 flag to true
 to exit the application.SDL_KEYDOWN
 event, we check if the pressed key is the Escape key ( SDLK_ESCAPE
) to quit the application. Otherwise, we print the name of the pressed key using SDL_GetKeyName
.SDL_MOUSEBUTTONDOWN
 event, we print the mouse button that was pressed using event.button.button
.SDL_MOUSEMOTION
 event, we print the current mouse position using event.motion.x
 and event.motion.y
.You can extend this event handling code to include additional event types and perform specific actions based on your application's requirements.
Remember to include the necessary headers and initialize SDL2 properly before handling events. Also, make sure to clean up resources, such as windows and renderers, before quitting the application.
Answers to questions are automatically generated and may not have been reviewed.
This guide walks you through the process of compiling SDL2, SDL_image, and SDL_ttf libraries from source