我正在尝试使箭头键在单行中的字符之间(左+右)以及自定义 shell(学期项目)的历史命令之间(上+下)移动。
此时,当点击其中一个箭头 ^[[A、^[[B、^[[C 或 ^[[D] 时,会显示出来,在按下 Enter 后,我发现其中一个箭头被按下:
char a = getchar();
if (a == '\033') {
getchar();
int ch2 = getchar();
switch(ch2){
case 'A':
printf("UP\n");
break;
case 'B':
printf("DOWN\n");
break;
case 'D':
printf("LEFT\n");
break;
case 'C':
printf("RIGHT\n");
break;
default:
printf("SOME OTHER SCROLL KEY PRESSED: %d %d\n", a, ch2);
break;
}
}
我想要得到的是,只要我击中其中一个箭头,就会发生操作而不显示任何内容。
最佳答案
默认情况下,unix 系统中的终端输入是行缓冲的,您可以使用 termios 为 stdin 函数指定自己的返回条件:
#include <stdio.h>
#include <termios.h>
static struct termios orig_termios;
char get_char_wait_for_keypress(void) {
struct termios raw;
// Get stdin file descriptor (0 by default)
int stdin_fileno = fileno(stdin);
// Copy terminal io settings
raw = orig_termios;
// Set return condition at first byte being received (For input timeout you can use `raw.c_cc[VTIME] = secs`)
raw.c_cc[VMIN] = 1;
// Apply settings with new return condition
tcsetattr(stdin_fileno, TCSANOW, &raw);
// Get char with new conditions
char c = getchar();
// Restore old settings
tcsetattr(stdin_fileno, TCSANOW, &orig_termios);
return c;
}
int main(void) {
struct termios raw;
char c = get_char_wait_for_keypress();
printf("%d", c);
}
关于c - 使用C语言在自定义shell中进行箭头键控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380560/