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

问题描述

是有可能有一个跨平台的方式来处理一个C或者Ocaml程序中的退格键和箭头键?

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

实际上是一个OCaml的解决办法是AP preciated但很多标准的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.

什么我要做到的,是赶上箭头键(由repropting最后一行或操作这样的),以覆盖其内壳行为。我认为这件事情的实际程序之前下降,它不是由code本身处理,所以我不知道这是否是可能的。

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,Mac 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..

推荐答案

我做过类似的东西pretty最近(虽然我的code不仅是Linux的)。你要标准输入为了读取箭头键presses设置为非标准模式。这应该在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 tsdin TCSAFLUSH terminfo); (* reset stdin when you quit*)
    tcsetattr stdin TCSAFLUSH newterminfo;

在标准模式下是关闭的,你并不需要等待一个换行符,以便从标准输入读取。 c_vmin重新presents字符返回之前阅读的最低数量(你可能希望能够在一次读取单个字符)和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,这样箭头键presses打印到终端(但你必须手动打印一切别的。

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.

大多数终端重新使用的present箭头键presses。如果您运行不带任何参数,并开始打方向键就可以看到使用的转义序列。它们通常

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 - "\027[A"
down - "\027[B"
left - "\027[D"
right - "\027[C"

在哪里'\\ 027'是 ESC

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

08-20 01:35