linux 应用层模拟按键输入


  1. #include <linux/input.h>  
  2. #include <sys/types.h>  
  3. #include <sys/stat.h>  
  4. #include <fcntl.h>  
  5. #include <unistd.h>  
  6. #include <stdint.h>  
  7. #include <stdio.h>  
  8.   
  9. /* 
  10. struct input_event { 
  11.     struct timeval time; 
  12.     __u16 type; 
  13.     __u16 code; 
  14.     __s32 value; 
  15. }; 
  16.  
  17. #define EV_KEY                  0x01 
  18. */  
  19. int reportkey(int fd, uint16_t type, uint16_t keycode, int32_t value)  
  20. {  
  21.     struct input_event event;  
  22.   
  23.     event.type = type;  
  24.     event.code = keycode;  
  25.     event.value = value;  
  26.   
  27.     gettimeofday(&event.time, 0);  
  28.   
  29.     if (write(fd, &event, sizeof(struct input_event)) < 0) {  
  30.         printf("report key error!\n");  
  31.         return -1;  
  32.     }  
  33.   
  34.     return 0;  
  35. }  
  36.   
  37. #define DEVNAME "/dev/input/event4"  
  38.   
  39. #define KEYDOWN 1  
  40. #define KEYUP   0  
  41.   
  42. int main(int argc, char *argv[])  
  43. {  
  44.     uint16_t keycode;  
  45.   
  46.     int k_fd;  
  47.   
  48.     k_fd = open(DEVNAME, O_RDWR);  
  49.   
  50.     if (k_fd < 0) {  
  51.         printf("open error!\n");  
  52.         return k_fd;  
  53.     }  
  54.   
  55.     keycode = KEY_A;  
  56.     reportkey(k_fd, EV_KEY, keycode, KEYDOWN);  
  57.     reportkey(k_fd, EV_KEY, keycode, KEYUP);  
  58.   
  59.     close(k_fd);  
  60.   
  61.     return 0;  
  62. }
上述代码是网上的一份代码,在运行过程中发现并没有起作用,愿意是发送按键后没有发送同步信号,每次reportkey后都再次reportkey(k_fd, 0, 0, 0)才行,也就是代码中的reportkey(k_fd,EV_KEY,keycode,KEYDOWN);reportkey(k_fd,EV_KEY,keycode,KEYDOWN);改为reportkey(k_fd,EV_KEY,keycode,KEYDOWN);reportkey(k_fd, 0, 0, 0);reportkey(k_fd,EV_KEY,keycode,KEYDOWN);reportkey(k_fd, 0, 0, 0);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值