ceventskeysdlkeylistener

Read Key presses in C; ex.: Arrow keys, Enter key


I know how to use events to test when a key is pressed or not, but in C I never found out how to do that.

What I want exactly is a "KeyListener" that listens for the Up, Down, Left and Right arrow keys. I need it to work in Linux, so no Windows libraries. And, if possible, using no 3rd party libraries is the best option for me.

Pseudocode of what I want:

int main() {
 
    // key listener {
    // if(key == up) { // do something }
    // if(key == down) { // do something }
    // if(key == left) { // do something }
    // if(key == right) { // do something }
    // }
}

Solution

  • How about using SDL to read the keyboard too.

      SDL_Event event;
      .
      .
      /* Poll for events. SDL_PollEvent() returns 0 when there are no  */
      /* more events on the event queue, our while loop will exit when */
      /* that occurs.                                                  */
      while( SDL_PollEvent( &event ) ){
        /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
        switch( event.type ){
          case SDL_KEYDOWN:
            printf( "Key press detected\n" );
    
            if (event.key.keysym.sym==SDLK_UP) 
                printf( "It was the UP key\n" );
    
            break;
          case SDL_KEYUP:
            printf( "Key release detected\n" );
            break;
    
          default:
            break;
        }
      }
      .
      .
    

    Source: http://www.libsdl.org/docs/html/guideinputkeyboard.html