Search code examples
c++linuxkeyboard

keyboad key codes table on Linux


I'm learning C++.

I'm testing how to which key has pressed the user. I have written this code:

#include <signal.h>
#include <termios.h>
#include <stdio.h>
#include <math.h>

#define KEYCODE_L 0x44 // Left Arrow Key
#define KEYCODE_R 0x43 // Right Arrow Key
#define KEYCODE_U 0x41 // Up Arrow Key
#define KEYCODE_D 0x42 // Down Arrow Key
#define KEYCODE_Q 0x71 // Q Key

int main(int argc, char **argv)
{
  // get the console in raw mode
  tcgetattr(kfd, &cooked);
  memcpy(&raw, &cooked, sizeof(struct termios));
  raw.c_lflag &= ~(ICANON | ECHO);

  // Setting a new line, then end of file
  raw.c_cc[VEOL] = 1;
  raw.c_cc[VEOF] = 2;
  tcsetattr(kfd, TCSANOW, &raw);

  puts("Reading from keyboard");
  puts("---------------------------");
  puts("Use arrow keys to move the robot.");

  // get the next event from the keyboard
  if (read(kfd, &c, 1) < 0)
  {
    perror("read():");
     /**
     * Reset console to its original mode.
     */
     tcsetattr(kfd, TCSANOW, &cooked);
     exit(-1);
  }

  switch (c)
  {
   case KEYCODE_R:
     std::cout << "Right Arrow" << std::endl;
      break;
   case KEYCODE_L:
     std::cout << "Left Arrow" << std::endl;
      break;
    case KEYCODE_U:
     std::cout << "Up Arrow" << std::endl;
      break;
    case KEYCODE_D:
     std::cout << "Down Arrow" << std::endl;
      break;
  }
}

Where can I find a table for all of those values that I have called KEYCODE_?

I’m looking for a table with the values for all the keys. I have found a JavaScript table but the values doesn't match.


Solution

  • Those are Ascii code given to you by the terminal. You can see them by using showkey -a command in Linux.

    More info on this command is available in man page, and online, for example, https://linux.die.net/man/1/showkey