Koko
Koko

Reputation: 479

How can I read the arrow keys in a Ruby curses application?

I have a Ruby curses application in which I'd like to trap for the arrow keys and function keys. The problem is that some keystrokes generate multiple values when using STDIN.getch. When I type a 'regular' key like a-z I get a single value back. When I type a [F]key or arrow key I get three values back.

Is there a gem designed for handling keyboard input or a better way to accomplish reading keystrokes?

#!/usr/bin/ruby

require 'curses'
require 'io/console'

Curses.noecho

Curses.init_screen
main_window = Curses::Window.new(24, 40, 1, 0)

num_keys = 0
loop do
   ch = STDIN.getch
   num_keys = num_keys + 1
   main_window.addstr(' key:' + ch.inspect + ' count:' + num_keys.to_s)
   main_window.refresh

   break if ch == 'q'
end

Curses.close_screen

Upvotes: 2

Views: 532

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

Trying enabling the keypad on the window right after you instantiate it.

main_window = Curses::Window.new(24, 40, 1, 0)
main_window.keypad = true

and then instead of using STDIN.getch there's a getch method on the window as well you can use, so try changing

ch = STDIN.getch

to

ch = main_window.getch

now when I run your program, I get

key: 259 count: 1

when I hit the up arrow instead of

key:"\e" count 1 key:"[" count:2 key:"A" count:3

Upvotes: 1

Related Questions