linux C获取键盘信息

1、利用Input子系统来获取信息
通过如下命令获取键盘对应的event id

cat /proc/bus/input/devices

我的电脑对应的是event4,实现代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <linux/input.h>

#define INPUT_KEYBOARD "/dev/input/event4"

int get_key_board_from_input()
{
    int fd = -1, ret = -1;
    struct input_event ev;

    fd = open(INPUT_KEYBOARD , O_RDONLY);
    if(fd < 0) {
        printf("open failed, error:%d\n", errno);
        return -1;
    }

    while(1) {
        memset(&ev, 0, sizeof(struct input_event));

        ret = read(fd, &ev, sizeof(struct input_event));
        if (ret != sizeof(struct input_event)) {
            printf("read error, ret: %d\n", ret);
            break;
        }

        if (ev.type == EV_KEY) {
            printf("--------------------\n");
            printf("type = %u.\n", ev.type); /* 消息类型,EV_KEY是按键 */
            printf("code = %u.\n", ev.code); /* 按键信息,/usr/include/linux/input-event-codes.h文件中有定义键值,例如KEY_ESC对应esc按键 */
            printf("value = %u.\n", ev.value); /* 按键是按下还是释放,0释放、1按下、2长按 */
        }
    }

    close(fd);
    return ret;
}

这个方法能很全面的获取按键的信息,但是不便的是需要root权限来运行

2、通过更改控制台设置,获取键盘值ASCII码

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int get_key_board_from_termios()
{
    int key_value;
    struct termios new_config;
    struct termios old_config;

    tcgetattr(0, &old_config);
    new_config = old_config;
    new_config.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(0, TCSANOW, &new_config);

    key_value = getchar();

    tcsetattr(0, TCSANOW, &old_config);

    printf("key_value: %d\n", key_value);
    return 0;
}

无需root权限即可执行

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值