Ruby键盘事件处理 [英] Ruby Keyboard event handling

查看:222
本文介绍了Ruby键盘事件处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我使用curses开发了一个小型控制台应用程序.

我有一个等待用户输入的主循环部分,它使用getstr函数,当然,这要等待用户按Enter键.

我想捕获向上和向下以及选项卡上的按键.我想用getstr无法做到这一点.

任何人都知道如何执行此操作吗?

我尝试使用STDIN.getc阻止应用程序运行,并且getch不能捕获箭头键

编辑#2:我在Windows上尝试此代码.看来Curses.getch适用于linux,但是在Windows上我没有收到向上箭头的键.

解决方案

您需要设置tty的"cbreak"模式,以便立即获得按键.如果您不这样做,则Unix终端处理系统将缓冲输入,直到收到换行符(即用户按下ENTER),然后所有输入都将移交给该进程.

这实际上不是特定于Ruby的,甚至不是特定于curses的;这是通过Unix tty运行的所有应用程序的工作方式.

尝试使用curses库cbreak()函数打开此模式.不要忘记在退出前致电nocbreak()将其关闭!

要读取单个字符,STDIN.getc将返回该字符的ASCII码的Fixnum. STDIN.read(1)可能会更方便,因为它返回下一个字符的一个字符的字符串.

但是,您会发现上/下"键(实际上是箭头键)实际上是一个字符序列.例如,在当今大多数类似于ANSI的终端仿真器(例如xterm)上,向上箭头将是"\e[A"(\e是转义字符).有termcap(终端功能)数据库可以处理此类问题,您可以通过curses访问它们,但实际上,您可能会发现,最简单的方法就是尝试直接解释这些内容,这是最简单的方法.这些天,您不太可能会使用ANSI代码以外的其他语言进入终端.

Hello im using curses to develop a small console application.

I have a main loop section wich 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 wich blocks the application from running, and getch doesnt catch the arrow keys

EDIT #2 : im 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.

解决方案

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.

这篇关于Ruby键盘事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆