Reputation: 255
I need to create an input box in a SDL window.
Since there is no function for that I am going to make a basic input box, but I can't find how to detect which key is pressed in SDL.
With this code below, I can print when I hit 'A'
but i think making this for each character will be really repetitive. How can I detect which key is pressed?
case: SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_a:
cout << "You Clicked \'A\'" << endl;
break;
}
Upvotes: 0
Views: 5558
Reputation: 11
This answer is great but I figured I would add some code to illustrate what it means for future visitors.
You can either save or cast the SDL_Keysym::sym
to a char
to output the corresponding text:
while (SDL_PollEvent(&sdlEvent)) {
if (sdlEvent.type == SDL_KEYDOWN && sdlEvent.key.keysym.sym >= 33 && sdlEvent.key.keysym.sym <= 126) { // Printable keys are 33 - 126
std::cout << (char)sdlEvent.key.keysym.sym;
}
}
Upvotes: 1
Reputation: 181745
SDL_Keysym::sym
is an SDL_Keycode
value. As you can see in the lookup table, these keycodes just correspond to ASCII values where possible. Checking if it's between 0x20
and 0x7f
(inclusive) should be a decent way to detect that.
You can also use SDL_GetKeyName
to get the name of the key as a string.
Note that modifiers like Shift are not taken into account. I assume that's okay because you asked for detecting key presses, not typed characters. Otherwise, SDL_TextInputEvent
is probably closer to what you need.
Upvotes: 7