使用C语言的自定义外壳中的箭头键控制

问题描述 投票:1回答:1

我正在尝试使箭头键在一行中的字符之间移动(左+右),并且在自定义外壳程序(学期项目)中在历史记录的命令之间(上+下)移动。

[此时,当击中箭头^ [[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;
    }
}

我想得到的是,只要我按下箭头之一,动作就会立即发生而不会显示任何内容。

c shell getchar arrow-keys
1个回答
3
投票

默认情况下,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);
}
© www.soinside.com 2019 - 2024. All rights reserved.