1

I'm using curses to develop a small console application.

I have a main loop section which waits for user input, it uses the getstr function, of course this waits for the user to press enter.

I would like to capture the up and down and tab keypresses. I suppose this can't be done with getstr.

Anyone have any idea how to do this?

EDIT: I've tried using STDIN.getc wihch blocks the application from running, and getch doesn't catch the arrow keys.

EDIT #2: I'm trying this code on Windows. It seems that Curses.getch works for Linux, but on Windows I get no key sent for the up arrow.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Nuno Furtado
  • 4,548
  • 8
  • 37
  • 57

2 Answers2

4

You need to set the "cbreak" mode of the tty so that you get keypresses immediately. If you don't do this, the Unix terminal-handling system will buffer the input until a newline is received (i.e., the user hits ENTER), and the input will all be handed to the process at that point.

This isn't actually Ruby- or even curses-specific; this is the way all applications work that run through a Unix tty.

Try using the curses library cbreak() function to turn on this mode. Don't forget to call nocbreak() to turn it off before you exit!

For reading a single character, STDIN.getc will return a Fixnum of the ASCII code of the character. Quite possibly you'll find STDIN.read(1) to be more convenient, since it returns a one-character string of the next character.

However, you'll find that the "up/down" keys,if by that you mean the arrow keys, are actually a sequence of characters. On most ANSI-like terminal emulators these days (such as xterm), the up arrow will be "\e[A" (that \e is an escape character) for example. There are termcap (terminal capability) databases to deal with this sort of thing, and you can access them through curses, but intially you may find it easiest just to experiment with interpreting these directly; you're not very likely to run into a terminal using anything other than ANSI codes these days.

cjs
  • 25,752
  • 9
  • 89
  • 101
  • thx for the answer im going to try that now, btw can you tell me what crmode function does? – Nuno Furtado May 22 '09 at 14:25
  • I'd not heard of crmode and nocrmode, but according to http://redmine.ruby-lang.org/issues/show/916 , they're just aliases for cbreak and nocbreak (now that the bug is fixed). – cjs May 23 '09 at 04:55
  • then using crmode or cbrak would be the same thing?!. – Nuno Furtado May 25 '09 at 09:13
  • For some reason when i use STDIN.getc my ruby program wont run, just sits idly there and wont start the application – Nuno Furtado May 25 '09 at 11:22
0

you want getch rather than getstr. also see curt sampson's comment about the arrow keys not being a single character.

Martin DeMello
  • 11,876
  • 7
  • 49
  • 64