功能:鼠标指针发神经不停做圆周运动
所需知识:模拟linux鼠标,圆的参数方程
开发环境:ubuntu 16.04LTS
1:如何模拟鼠标?
linux 内核为了处理各种不同类型的输入设备(比如说鼠标,键盘,操纵杆,触摸屏等)设计并实现了一个对上层应用统一的试图的抽象层,即是linux输入子系统.
这个input子系统可以很容易地让我们在用户空间模拟鼠标和键盘事件。例如,你可以写一个应用程序,往input子系统的/dev/input/event3设备文件(假设这个是
键盘设备文件)写入A,这样就相当于你通过键盘按下了A,而这个A对系统任意的一个当前活动窗口有效(捕捉)。同样,我们也可以找到鼠标的设备文件并向里面
写入坐标等数据来实现鼠标指针的移动.
2:如何控制鼠标移动?
首先我们需要找到鼠标的设备文件,打开控制台输入cat /proc/bus/input/devices | grep mouse 我的笔记本显示如下结果:
为什么会有两个呢(随便用哪一个都一样)?笔记本嘛,有一个触摸板,我本身也有个无线鼠标(你也可以不使用gerp mouse命令,可以查看更详细的信息).于是我可以向/dev/input/event9里面写数据来控制鼠标.
那么问题就来了,到底往/dev/input/event9文件中写什么数据才能控制鼠标指针移动呢?
在/usr/include/linux/input.h中有定义,这个文件定义了event事件的结构体,API和标准按键的编码等;我们需要做的是将要写入的按键编码填充到结构体中,然后写入/dev/input/event9文件中.
输入事件的结构体:
struct input_event
{
struct timeva l time;//按键时间
_u16 type;//按键类型
_u16 code;//要模拟成什么按键
_s32 value;//是按下1还是释放0
};
如果事件的类型代码是EV_REL(相对坐标移动) value的正数值和负数值分别代表两个不同方向的值.例如:如果code是REL_X value是10的话,就表示鼠标相对于上一次的坐标,往x轴向右移动10个像素点.
4:程序代码
//文件名:sim.c
#include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <linux/input.h> #include <linux/uinput.h> #include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <math.h> void simulate_mouse(int fd,int x,int y) { struct input_event event; memset(&event, 0, sizeof(event)); gettimeofday(&event.time, NULL); event.type = EV_REL; event.code = REL_X; event.value = x; write(fd, &event, sizeof(event)); event.type = EV_REL; event.code = REL_Y; event.value = y; write(fd, &event, sizeof(event)); event.type = EV_SYN;//同步 event.code = SYN_REPORT; event.value = 0; write(fd, &event, sizeof(event)); } int main() { int rx,ry; int i; int fd_mouse; double theta1=90,pertheta,theta0=90; fd_mouse = open("/dev/input/event9", O_RDWR);//你的电脑可能不是event9哦,具体看这篇博文上面 if(fd_mouse <= 0) { printf("error open mouse\n"); return -2; } pertheta=360.0/360;//每次减少1度 int r=400; while(1) { theta1=90; theta0=90; for(i=0;i<360;i++) { rx = (int)(r*cos(theta1/180.0*3.141592653589792)-r*cos(theta0/180.0*3.1415926535897922));//求相对移动的像素 ry = (int)(r*sin(theta1/180.0*3.141592653589792)-r*sin(theta0/180.0*3.141592653589792));//求相对移动的像素 simulate_mouse(fd_mouse,rx,ry); theta0=theta1; theta1=theta1-pertheta; usleep(20000); } } close(fd_mouse); }
编译使用gcc sim.c -o sim -lm 因为使用了math.h 所以需要加-lm
运行需要root权限!!!!!!!所以要sudo一下哦.