Linux 使用uinput创建虚拟input设备

http://blog.csdn.net/mcgrady_tracy/article/details/22938181

 

参考了这里:http://thiemonge.org/getting-started-with-uinput


代码如下:

    1. #include <linux/input.h>  
    2. #include <linux/uinput.h>  
    3. #include <sys/types.h>  
    4. #include <sys/stat.h>  
    5. #include <fcntl.h>  
    6. #include <unistd.h>  
    7. #include <string.h>  
    8. #include <stdint.h>  
    9. #include <stdio.h>  
    10.   
    11. int reportkey(int fd, uint16_t type, uint16_t keycode, int32_t value)  
    12. {  
    13.     int ret;  
    14.   
    15.     struct input_event ev;  
    16.   
    17.     memset(&ev, 0, sizeof(struct input_event));  
    18.   
    19.     ev.type = type;  
    20.     ev.code = keycode;  
    21.     ev.value = value;  
    22.   
    23.     ret = write(fd, &ev, sizeof(struct input_event));  
    24.     if (ret < 0) {  
    25.         printf("report key error!\n");  
    26.         return ret;  
    27.     }  
    28.   
    29.     printf("key is %d %d\n", keycode, value);  
    30.   
    31.     return 0;  
    32. }  
    33.   
    34. int main(void)  
    35. {  
    36.     struct uinput_user_dev uidev;  
    37.   
    38.     int fd, ret;  
    39.   
    40.     fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);  
    41.   
    42.     if (fd < 0) {  
    43.         return fd;  
    44.     }  
    45.   
    46.     ret = ioctl(fd, UI_SET_EVBIT, EV_KEY);  
    47.     ret = ioctl(fd, UI_SET_EVBIT, EV_SYN);  
    48.   
    49.     ret = ioctl(fd, UI_SET_KEYBIT, KEY_D);  
    50.   
    51.     memset(&uidev, 0, sizeof(struct uinput_user_dev));  
    52.   
    53.     snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-sample");  
    54.     uidev.id.bustype = BUS_USB;  
    55.     uidev.id.vendor = 0x1234;  
    56.     uidev.id.product = 0xfedc;  
    57.     uidev.id.version = 1;  
    58.   
    59.     ret = write(fd, &uidev, sizeof(struct uinput_user_dev));  
    60.   
    61.     ret = ioctl(fd, UI_DEV_CREATE);  
    62.     if (ret < 0) {  
    63.         close(fd);  
    64.         return ret;  
    65.     }  
    66.   
    67.     while (1) {  
    68.         reportkey(fd, EV_KEY, KEY_D, 1);  
    69.         reportkey(fd, EV_SYN, SYN_REPORT, 0);  
    70.         reportkey(fd, EV_KEY, KEY_D, 0);  
    71.         reportkey(fd, EV_SYN, SYN_REPORT, 0);  
    72.         sleep(1);  
    73.     }  
    74.   
    75.     ioctl(fd, UI_DEV_DESTROY);  
    76.   
    77.     close(fd);  
    78.   
    79.     return 0;  
posted @ 2014-11-23 01:54  alxe_yu  阅读(1597)  评论(0)    收藏  举报