How to get Ctrl, Shift or Alt with getch() ncurses?

klefevre picture klefevre · Mar 17, 2012 · Viewed 23.4k times · Source

How to get Ctrl, Shift or Alt with getch() ncurses ?
I cannot get it work to get Ctrl, Shift or Alt with getch() using ncurses ? Do I miss something in the man ?

Answer

Technologeeks picture Technologeeks · Sep 26, 2015

Amazing how sometimes the right answer gets demoted, and answers that "authoritatively" give up get promoted... With a bit of creativity, key_name actually holds the right key to figuring this out, with one caveat - that SHIFT/ALT/CTRL are pressed with other keys at the same time:

  • First, for "normal keys" such as the printable ones, you can easily detect shift because it uppercases.

  • For special keys, e.g. KEY_LEFT, you will see that the code generated when SHIFT is selected is actually KEY_SLEFT. ditto for KEY_RIGHT. Unfortunately, no such luck for KEY_UP/KEY_DOWN , which seem unfazed by SHIFT. So you can distinguish by the returned char from getch() - the KEY_S.. implies shift was pressed.

  • For ALT (what's not trapped by X or the Aqua Windowmanager, at least), keyname will convert the key to an M... something.

  • For CTRL you'll get a "^" preceding the actual key name. E.g ^R for key 18

So you can now figure out the key codes for your switch(getch) statements, etc, by a simple snippet:

ch = getch(); endwin(); printf("KEY NAME : %s - %d\n", keyname(ch),ch);

and that's that. Think before definitively saying "can't". Maybe there's a way that's less obvious.