Search code examples
escapingncursesarrow-keystermios

How to differentiate between Escape and Up/Down/Left/Right with termios?


GitHub

This is the best I can come up with to handle ncurses-style key presses (I'm actually writing an alternative to ncurses for various reasons).

An example app built with this code advises the user to "Quit by pressing Escape". In truth, it requires Escape + Escape or Escape + An Arrow Key. I'd like to fix this.

#include <sys/ioctl.h>
#include <termios.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *get_key() {
    char c = getchar();

    switch(c) {
        case 'a': return "a";
        case 'b': return "b";
        case 'c': return "c";

        ...

        case '\x1b':
            c = getchar();
            switch(c) {
                case '[':
                    c = getchar();
                    switch(c) {
                        case 'A': return "up";
                        case 'B': return "down";
                        case 'C': return "right";
                        case 'D': return "left";
                    }
                case '\x1b': return "escape";
            }

        default: return "unknown";
    }

Solution

  • A buffer and some bit options do the job nicely.

    GitHub