Ruby 键盘事件处理
我正在使用curses 开发一个小型控制台应用程序。
我有一个等待用户输入的主循环部分,它使用 getstr 函数,当然这会等待用户按 Enter 键。
我想捕获向上、向下和 Tab 按键。 我想这不能用 getstr 来完成。
有人知道如何做到这一点吗?
编辑:我尝试使用 STDIN.getc wihch 阻止应用程序运行,并且 getch 无法捕获箭头键。
编辑#2:我正在 Windows 上尝试此代码。 Curses.getch 似乎适用于 Linux,但在 Windows 上我没有收到向上箭头发送的密钥。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要 getch 而不是 getstr。 另请参阅 curt sampson 关于箭头键不是单个字符的评论。
you want getch rather than getstr. also see curt sampson's comment about the arrow keys not being a single character.
您需要设置 tty 的“cbreak”模式,以便立即按下按键。 如果不这样做,Unix 终端处理系统将缓冲输入,直到收到换行符(即用户按
ENTER
),并且输入将全部传递给进程那一点。这实际上不是 Ruby 或诅咒特定的; 这是所有通过 Unix tty 运行的应用程序的工作方式。
尝试使用curses库
cbreak()
函数来打开此模式。 不要忘记在退出之前调用nocbreak()
将其关闭!对于读取单个字符,
STDIN.getc
将返回该字符的 ASCII 代码的 Fixnum。 您很可能会发现STDIN.read(1)
更方便,因为它返回下一个字符的单字符字符串。但是,您会发现“向上/向下”键(如果您指的是箭头键)实际上是一个字符序列。 如今,在大多数类似 ANSI 的终端仿真器(例如 xterm)上,向上箭头将为“
\e[A
”(\e
是转义字符)例子。 有 termcap(终端功能)数据库可以处理此类事情,您可以通过curses 访问它们,但最初您可能会发现直接尝试解释它们是最简单的; 如今,您不太可能遇到使用 ANSI 代码以外的任何代码的终端。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 callnocbreak()
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 findSTDIN.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.