如何读取 Ruby curses 应用程序中的箭头键?

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

我有一个 Ruby curses 应用程序,我想在其中捕获箭头键和功能键。问题是某些击键在使用 STDIN.getch 时会生成多个值。当我键入 'regular' 键时,如 a-z 我得到一个单一的值。当我键入 [F] 键或箭头键时,我会返回三个值。

是否有 gem 设计用于处理键盘输入或更好的方法来完成阅读击键?

#!/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

实例化后立即尝试在 window 上启用 keypad

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

然后你可以使用 window 上的 getch 方法而不是使用 STDIN.getch,所以尝试更改

ch = STDIN.getch

ch = main_window.getch

现在当我 运行 你的程序时,我得到

key: 259 count: 1

当我点击向上箭头而不是

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