SDL2: Best Way To Read [Enter], [Back Space], & [Space] Keys?


Working on input today again.
I need to get the status of the [Enter], [Back Space], and [Spacebar] keys.
What would be the best way to do the above?
I am currently using TEXTINPUT events to read printable character keys.


Ok so I looked at an ASCII table here:

I see [Enter], [Back Space], and [Spacebar].
But how do I detect those with:

char c = Event.text.text[0];
if(c < ’ ’ || c > ‘~’) break;

KeyOnKeyboardPressedByUser = (char)c;


Like for [Back Space] is char “BS” - do I check:
Event.text.text[0] = “B” && Event.text.text[1] = “S” ?
// Can the above be shortened to “BS” - like some string compare function or something?

Thanks, sorry for all the questions…


I’d Check for backspace and enter using SDL_KEYDOWN, and then edit the string of the input accordingly.

If you really want to check for raw ascii values, you can do so by just comparing to the number listed in the ascii table or by using the “\x” escape sequence with the hex number(’\x0A’ for the line feed, to give an example). Im honestly not sure if SDL_TEXTINPUT provides the sequence for backspace though.

As I understand it, SDL_TEXTINPUT is used for actual text inputs - if you want the user to input a string somewhere. If you want to check for inputs (controls like up, down, enter key, …), you check against the keydown or mouse events.

I implemented textinput at some point - its ugly as hell but it worked. Its in D - API and type names are the same, just a bit different syntax. Maybe this helps you a bit

Ok, got it working

    case SDL_KEYDOWN:
            char keyDown = Event.key.keysym.scancode;

            if (keyDown == SDL_SCANCODE_RETURN)  EnterKeyPressed = true;
            else if (keyDown == SDL_SCANCODE_BACKSPACE)  BackSpaceKeyPressed = true;
            else if (keyDown == SDL_SCANCODE_SPACE)  SpacebarKeyPressed = true;
            else if (keyDown == SDL_SCANCODE_ESCAPE)  EscapeKeyPressed = true;