根據下列網站,練習了一下 the user level input subsystem

http://thiemonge.org/getting-started-with-uinput

 

以下為source code,其效果為 ubtune 桌面上的 Terminal會秀出 "ddddd"

 

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>

#include <errno.h>

#include <linux/input.h>

#include <linux/uinput.h>

 

 

int main(void)

{

int fd;

int ret;

struct uinput_user_dev uidev;

struct input_event ev;

int i;

 

// open /dev/uinput device

fd=open("/dev/uinput",O_WRONLY | O_NONBLOCK);

if(fd<0){

printf("open uinput fail \r\n");

exit(EXIT_FAILURE);

}

printf("open uinput successfully \r\n");

 

//

ret=ioctl(fd,UI_SET_EVBIT,EV_SYN);

if(ret<0){

printf("ioctl EV_SYN fail \r\n");

exit(EXIT_FAILURE);

}

 

//

ret=ioctl(fd,UI_SET_EVBIT,EV_KEY);

if(ret<0){

printf("ioctl EV_KEY fail \r\n");

exit(EXIT_FAILURE);

}

 

ret=ioctl(fd,UI_SET_KEYBIT,KEY_D);

if(ret<0){

printf("ioctl KEY_D fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("ioctl KEY_D ok \r\n");

}

 

 

memset(&uidev, 0, sizeof(uidev));

 

snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "yps-sample");

uidev.id.bustype = BUS_USB;

uidev.id.vendor = 0x1234;

uidev.id.product = 0xfedc;

uidev.id.version = 1;

 

ret = write(fd, &uidev, sizeof(uidev));

if(ret<0){

printf("write uidev fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("write uidev ok \r\n");

}

 

ret = ioctl(fd, UI_DEV_CREATE);

if(ret<0){

printf("UI_DEV_CREATE fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("UI_DEV_CREATE ok \r\n");

}

sleep(2); // must wait UI_DEV_CREATE ready

 

for(i = 0; i <5; i++) { // sleep 1 s than loop

printf("i=%d \r\n",i);

 

// key press

memset(&ev, 0, sizeof(ev));

ev.type = EV_KEY;

ev.code = KEY_D;

ev.value = 1;

ret = write(fd, &ev, sizeof(ev));

if(ret<0){

printf("KEY_D press fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("KEY_D press ok \r\n");

}

 

 

memset(&ev, 0, sizeof(ev));

ev.type = EV_SYN;

ev.code = SYN_REPORT;

ev.value = 0;

 

ret = write(fd, &ev, sizeof(ev));

if(ret<0){

printf("KEY_D sync \r\n");

exit(EXIT_FAILURE);

}else{

printf("KEY_D sync ok \r\n");

}

usleep(15000);

 

 

// key release

memset(&ev, 0, sizeof(ev));

ev.type = EV_KEY;

ev.code = KEY_D;

ev.value = 0;

 

ret = write(fd, &ev, sizeof(ev));

if(ret<0){

printf("KEY_D release fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("KEY_D release ok \r\n");

}

 

 

memset(&ev, 0, sizeof(ev));

ev.type = EV_SYN;

ev.code = SYN_REPORT;

ev.value = 0;

 

ret = write(fd, &ev, sizeof(ev));

if(ret<0){

printf("EV_SYN SYN_REPORT fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("EV_SYN SYN_REPORT ok \r\n");

}

 

usleep(15000);

 

 

 

}

 

printf("loop end \r\n");

sleep(1);

ret = ioctl(fd, UI_DEV_DESTROY);

if(ret<0){

printf("UI_DEV_DESTROY fail \r\n");

exit(EXIT_FAILURE);

}else{

printf("UI_DEV_DESTROY ok \r\n");

}

 

close(fd);

 

return;

}

CuteParrot 發表在 痞客邦 留言(0) 人氣()