Linux 设置控制台读取为异步,与上下左右,CTRL+C控制键判定

设置为异步读取键盘代码与还原示例:

struct termios term_settings;

// Force terminal input to read keyboard input asynchronously
SetKeyboardNonblocking(&term_settings);

// TO:DO Your are code here.

// Not restoring the keyboard settings causes the input from the terminal to not work right
RestoreKeyboardBlocking(&term_settings);

1、设置控制台读取为异步

    void SetKeyboardNonblocking(struct termios* initial_settings) {
        struct termios new_settings;
        tcgetattr(0, initial_settings);

        new_settings = *initial_settings;
        new_settings.c_lflag &= ~ICANON;
        new_settings.c_lflag &= ~ECHO;
        new_settings.c_lflag &= ~ISIG;
        new_settings.c_cc[VMIN] = 0;
        new_settings.c_cc[VTIME] = 0;

        tcsetattr(0, TCSANOW, &new_settings);
    }

2、欢迎控制台读取为?(若保存为同步则为同步)

    void RestoreKeyboardBlocking(struct termios* initial_settings) {
        tcsetattr(0, TCSANOW, initial_settings);
    }

3、判定键代码为上下左右,CTRL+C,需要设置为异步读入键代码模式

返回控制代码:

1、上

2、下

3、左

4、右

5、CTRL+C

static int
ReadConsoleControlKey() {
    static int key_list[3];
    static int key_index = 0;   
    int& key_code = key_list[key_index];
    key_code = getchar();
    if (key_code <= 0) {
        return 0;
    }
    if (key_index <= 0) {
        if (key_code == 27) {
            key_index++;
        }
        else {
            key_index = 0;
            if (key_code == 3) {
                return 5;
            }
        }
    }
    else if (key_index <= 1) {
        if (key_code == 91) {
            key_index++;
        }
        else {
            key_index = 0;
        }
    }
    else if (key_index <= 2) {
        key_index = 0;
        switch (key_code)
        {
        case 65:
            return 1;
        case 66:
            return 2;
        case 67:
            return 3;
        case 68:
            return 4;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值