2021-05-12 14:32:11
Linux環境下模擬滑鼠操作
2020-06-16 17:40:28
在Linux/input.h中定義了以下結構體型別,用於標準按鍵的編碼操作:
Struct input_evnet{
Struct timeval time; //按鍵時間
_u16 type;//型別
_u16 code;//模擬成什麼按鍵碼
_u32 value;//按下還是釋放
}
EV_KEY:表示鍵盤;EV_REL表示相對坐標;EV_ABS表示絕對坐標
若事件型別為EV_KEY,code為按鍵的鍵值碼,vaule為0表示釋放,value為1表示按下;若事件型別為EV_REL,code為REL_X(表示滑鼠的X軸方向)或者REL_Y(表示滑鼠的Y軸方向)。
模擬滑鼠輸入
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <Linux/input.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
/*
*模擬滑鼠軌跡球
*/
void simulate_mouse(int fd, int value)
{
struct input_event event;
memset(&event, 0, sizeof(event));
gettimeofday(&event.time, NULL);
event.type = EV_REL;
event.code = REL_X;//滑鼠x軸方向
event.value = value;//x軸方向相對位移
write(fd, &event, sizeof(event));//寫入
event.type = EV_REL;
event.code = REL_Y;//滑鼠y軸方向
event.value = value;//y軸方向相對位移
write(fd, &event, sizeof(event));//寫入
event.type = EV_SYN;//同步
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(event));
}
/*
*模擬滑鼠單擊,先按下後釋放
*/
void simulate_mouse_click(int fd,int value){
struct input_event event;
memset(&event, 0, sizeof(event));
gettimeofday(&event.time, NULL);
event.type = EV_KEY;
event.code = value;
event.value = 1;
if(write(fd,&event,sizeof(event)) < 0){
LOGE("mouse key write error.n");
}
event.type = EV_SYN;
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(event));
event.type = EV_KEY;
event.code = value;
event.value = 0;
if(write(fd,&event,sizeof(event)) < 0){
LOGE("mouse key write error.n");
}
event.type = EV_SYN;
event.code = SYN_REPORT;
event.value = 0;
write(fd, &event, sizeof(event));
return;
}
int main(void)
{
int fd_mouse;
int value = 0;
fd_mouse = open("/dev/input/event2", O_RDWR);//開啟裝置節點
if (fd_mouse <= 0)
{
printf("error open mousen");
return -2;
}
while (1)
{
value = 0;
for (value = 0; value < 10; value++)
{
simulate_mouse(fd_mouse, value);
usleep(20*1000);
}
getchar();
for (value = 0; value > -10; value--)
{
simulate_mouse(fd_mouse, value);
usleep(20*1000);
}
getchar();
}
simulate_mouse_click(fd_mouse,BTN_LEFT);//點選滑鼠左鍵
close(fd_mouse);
return 0;
}
相關文章