您的位置:首页 > 运维架构 > Linux

linux 应用层模拟按键输入

2016-02-18 09:14 435 查看
#include <linux/input.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <fcntl.h>  
#include <unistd.h>  
#include <stdint.h>  
#include <stdio.h>  
  
/* 
struct input_event { 
    struct timeval time; 
    __u16 type; 
    __u16 code; 
    __s32 value; 
}; 
 
#define EV_KEY                  0x01 
*/  
int reportkey(int fd, uint16_t type, uint16_t keycode, int32_t value)  
{  
    struct input_event event;  
  
    event.type = type;  
    event.code = keycode;  
    event.value = value;  
  
    gettimeofday(&event.time, 0);  
  
    if (write(fd, &event, sizeof(struct input_event)) < 0) {  
        printf("report key error!\n");  
        return -1;  
    }  
  
    return 0;  
}  
  
#define DEVNAME "/dev/input/event4"  
  
#define KEYDOWN 1  
#define KEYUP   0  
  
int main(int argc, char *argv[])  
{  
    uint16_t keycode;  
  
    int k_fd;  
  
    k_fd = open(DEVNAME, O_RDWR);  
  
    if (k_fd < 0) {  
        printf("open error!\n");  
        return k_fd;  
    }  
  
    keycode = KEY_A;  
    reportkey(k_fd, EV_KEY, keycode, KEYDOWN);  
    reportkey(k_fd, EV_KEY, keycode, KEYUP);  
  
    close(k_fd);  
  
    return 0;  
}

上述代码是网上的一份代码,在运行过程中发现并没有起作用,愿意是发送按键后没有发送同步信号,每次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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: