Finding key codes on Linux


It often happens that I get into a situation where I need to know key codes of pressed keys. On my Mac that’s simple. Just use the Key Codes by Many Tricks.

But on Linux I constantly was trying to find out which key produced what.

So I ended up writing a program for that. I started of in the shell, but that ended up being rather tricky and unnecessary complicated. So I redid the whole thing in C.

This is the result

/*
 * Program     : code.c
 * Author      : Ton Kersten
 */

#include <stdio.h>
#include <curses.h>

#define DONE	'q'
#define ESC		0x1b
#define SPC		0x20

char ch;

main()
{
	printf("Press '%c' to quit!\n\n", DONE);

	/*
	 * Put the terminal in raw mode, with no echo
	 */
	system("stty raw -echo");

	/*
	 * Print the header
	 */
	printf("%4s\t%4s\t%4s\t%4s\r\n", "Char", " Hex", " Oct", " Dec");
	printf("%4s\t%4s\t%4s\t%4s\r\n", "----", "----", "----", "----");

	/*
	 * Set the initial loop value to something odd
	 */
	ch: DONE-1;
	while ( ch != DONE )
	{	ch: getchar();

		/*
		 * Character read. Display it. Look out for < 0x20
		 */
		if ( ch < SPC )
		{	if ( ch == ESC )
			{	/*
				 * Esc. Just say 'Esc'
				 */
				printf("%-4s\t0x%02x\t%04o\t%04d\r\n",
						"Esc", ch, ch, ch);
			}
			else
			{	/*
				 * < ' '. Print Control character
				 */
				printf("^%-c\t0x%02x\t%04o\t%04d\r\n",
						ch-1+'A', ch, ch, ch);
			}
		}
		else
		{	/*
			 * Normal character. Display it normally
			 */
			printf("%-4c\t0x%02x\t%04o\t%04d\r\n",
						ch, ch, ch, ch);
		}
	}

	/*
	 * Put the terminal back to something usefull
	 */
	system("stty sane echo");
}

And this is an example of the output

Press 'q' to quit!

Char	 Hex	 Oct	 Dec
----	----	----	----
Esc 	0x1b	0033	0027
O   	0x4f	0117	0079
P   	0x50	0120	0080
Esc 	0x1b	0033	0027
[   	0x5b	0133	0091
2   	0x32	0062	0050
4   	0x34	0064	0052
~   	0x7e	0176	0126
q   	0x71	0161	0113
code  linux  sysadm 

See also