uinput示例,編譯好後運行,10秒內打開空白文本文件,10秒後會在文本文件裏輸入“l”字符。
示例源碼:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <linux/uinput.h>
#include <linux/input.h>
#include <sys/select.h>
#define KEY_CUSTOM_UP 0x20
#define KEY_CUSTOM_DOWN 0x30
static struct uinput_user_dev uinput_dev;
static int uinput_fd;
int creat_user_uinput(void);
int report_key(unsigned int type, unsigned int keycode, unsigned int value);
static void sleep_ms(unsigned int secs)
{
struct timeval tval;
tval.tv_sec=secs/1000;
tval.tv_usec=(secs*1000)%1000000;
select(0,NULL,NULL,NULL,&tval);
}
int main(int argc, char *argv[])
{
int ret = 0;
int i;
for(i=0;i<1000;i++){
sleep_ms(10);
if(i%100 == 0)
printf("=%d=\n", i);
}
ret = creat_user_uinput();
if(ret < 0){
printf("%s:%d\n", __func__, __LINE__);
return -1;//error process.
}
sleep(10);// help you to 'hexdump -C /dev/input/event[X]' for test.
report_key(EV_KEY, KEY_L, 1);// Report BUTTON A CLICK - PRESS event
report_key(EV_KEY, KEY_L, 0);// Report BUTTON A CLICK - RELEASE event
//report_key(EV_KEY, KEY_CUSTOM_UP, 12);
//report_key(EV_KEY, KEY_CUSTOM_UP, 0);
sleep(5);
close(uinput_fd);
return 0;
}
int creat_user_uinput(void)
{
int i;
int ret = 0;
uinput_fd = open("/dev/uinput", O_RDWR | O_NDELAY);
if(uinput_fd < 0){
printf("%s:%d\n", __func__, __LINE__);
return -1;//error process.
}
//to set uinput dev
memset(&uinput_dev, 0, sizeof(struct uinput_user_dev));
snprintf(uinput_dev.name, UINPUT_MAX_NAME_SIZE, "uinput-custom-dev");
uinput_dev.id.version = 1;
uinput_dev.id.bustype = BUS_VIRTUAL;
ioctl(uinput_fd, UI_SET_EVBIT, EV_SYN);
ioctl(uinput_fd, UI_SET_EVBIT, EV_KEY);
ioctl(uinput_fd, UI_SET_EVBIT, EV_MSC);
for(i = 0; i < 256; i++){
ioctl(uinput_fd, UI_SET_KEYBIT, i);
}
ioctl(uinput_fd, UI_SET_MSCBIT, KEY_CUSTOM_UP);
ioctl(uinput_fd, UI_SET_MSCBIT, KEY_CUSTOM_DOWN);
ret = write(uinput_fd, &uinput_dev, sizeof(struct uinput_user_dev));
if(ret < 0){
printf("%s:%d\n", __func__, __LINE__);
return ret;//error process.
}
ret = ioctl(uinput_fd, UI_DEV_CREATE);
if(ret < 0){
printf("%s:%d\n", __func__, __LINE__);
close(uinput_fd);
return ret;//error process.
}
}
int report_key(unsigned int type, unsigned int keycode, unsigned int value)
{
struct input_event key_event;
int ret;
memset(&key_event, 0, sizeof(struct input_event));
gettimeofday(&key_event.time, NULL);
key_event.type = type;
key_event.code = keycode;
key_event.value = value;
ret = write(uinput_fd, &key_event, sizeof(struct input_event));
if(ret < 0){
printf("%s:%d\n", __func__, __LINE__);
return ret;//error process.
}
gettimeofday(&key_event.time, NULL);
key_event.type = EV_SYN;
key_event.code = SYN_REPORT;
key_event.value = 0;//event status sync
ret = write(uinput_fd, &key_event, sizeof(struct input_event));
if(ret < 0){
printf("%s:%d\n", __func__, __LINE__);
return ret;//error process.
}
return 0;
}