linux 读取键盘值

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

char *GetKeyboardEventNum(char *kybName)
{
    char *p;
    char name[64]; /* RATS: Use ok, but could be better */
    char buf[256] = {
        0,
    }; /* RATS: Use ok */
    int fd = 0;
    int i;
    for (i = 0; i < 32; i++)
    {
        sprintf(name, "/dev/input/event%d", i);
        if ((fd = open(name, O_RDONLY, 0)) >= 0)
        {
            ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);
            if (strstr(buf, kybName))
            {
                close(fd);
                p = name;
                return p;
            }
            close(fd);
        }
    }
    return "";
}
typedef void (*func)(int); //定义函数类型

extern void GetKeyBoard(func callback);
void GetKeyBoard(func callback)
{
    int keys_fd; //文件标志
    char ret[2];
    struct input_event t; //读取到的input设备数据是一个结构体
    char *DEV_PATH = GetKeyboardEventNum("SIGMACHIP USB Keyboard");
    keys_fd = open(DEV_PATH, O_RDONLY); //权限不通过的时候一般会返回-1
    if (keys_fd <= 0)
    {
        // printf("open /dev/input/event2 device error!\n");
        return -1;
    }
    while (1)
    {
        if (
            read(keys_fd, &t, sizeof(t)) == sizeof(t)) /*keys_fd指向打开的设备文件,read将从设备文件传送sizeof(t)个字节的数据到&t这个内存地址。函数执行顺利的话返回值是实际读取的字节数*/
        {
            if (t.type == EV_KEY)
            {
                if (t.value == 1)
                {
                    printf("key %d\n", t.code); // t.code值所对应的按键在/usr/include/linux/input-event-codes.h可以查到
                    callback(t.code);
                    //printf("key %d %s\n", t.code, (t.value) ? "Pressed" : "Released"); // t.code值所对应的按键在/usr/include/linux/input-event-codes.h可以查到
                }
            }
        }
    }
    close(keys_fd);
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值