使用标准输入识别箭头键 [英] Recognizing arrow keys with stdin

查看:21
本文介绍了使用标准输入识别箭头键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以跨平台处理 C 或 OCaml 程序中的退格键和箭头键?

is it possible to have a cross-platform way to handle backspace and arrows keys within a C or OCaml program?

实际上 OCaml 解决方案会受到赞赏,但许多标准的 unix 函数被直接包装到相应的 API 调用中,因此移植 C 解决方案应该没有问题.

Actually an OCaml solution would be appreciated but many standard unix functions are wrapped directly to corresponding API calls so there's should be no problem in porting a C solution.

我要实现的是捕获箭头键以覆盖其在 shell 内的行为(通过重新传播最后一行或类似的操作).我觉得这个东西在实际程序之前,它不是由代码本身处理的,所以我不知道是否可能.

What I'm going to achieve is to catch the arrow keys to override its behaviour inside the shell (by repropting last line or operations like these). I think that this thing falls before the actual program and it's not handled by code itself so I don't know if it's possible.

该程序是在 Linux、OS X 和 Windows(在 cygwin 上)上编译的,所以我想在所有平台上都这样做..

The program is compiled either on Linux, OS X and Windows (on cygwin) so I would like to do it for all platforms..

推荐答案

我最近做了一些非常相似的事情(尽管我的代码仅适用于 Linux).您必须将 stdin 设置为非规范模式才能读取箭头键按下.这应该适用于 OS X 和 Linux,并且可能适用于 Cygwin,尽管我不能肯定.

I've done something pretty similar recently (although my code is Linux only). You have to set stdin to non-canonical mode in order to read arrow key presses. This should work on OS X and Linux and will probably work on Cygwin although I can't say for sure.

open Unix
let terminfo = tcgetattr stdin in
  let newterminfo = {terminfo with c_icanon = false; c_vmin = 0; c_vtime = 0} in
    at_exit (fun _ -> tcsetattr stdin TCSAFLUSH terminfo); (* reset stdin when you quit*)
    tcsetattr stdin TCSAFLUSH newterminfo;

当规范模式关闭时,您无需等待换行符即可从标准输入读取.c_vmin 表示返回前要读取的最少字符数(您可能希望一次读取一个字符),c_vtime 是最大读取等待时间(以 0.1 秒为单位).

when canonical mode is off, you don't need to wait for a newline in order to read from stdin. c_vmin represents the minimum numbers of characters to read before returning (you probably want to be able to read a single character at a time) and c_vtime is the maximum read wait time (in 0.1s units).

您可能还想将 c_echo 设置为 false,以便将箭头键按下打印到终端(但您必须手动打印其他所有内容.

You might also want to set c_echo to false so that the arrow key presses are printed to the terminal (but then you'll have to manually print everything else.

大多数终端使用 ANSI 转义序列表示箭头键按下.如果您不带参数运行 cat 并开始按箭头键,您可以看到使用的转义序列.他们通常是

Most terminals represent arrow key presses using ANSI escape sequences. If you run cat with no arguments and start hitting the arrow keys you can see the escape sequences used. They are typically

up - "33[A"
down - "33[B"
left - "33[D"
right - "33[C"

其中 '33' 是 esc

Where '33' is the ascii value for esc

这篇关于使用标准输入识别箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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