本文主要是介绍在ubuntu18.04下,通过编程向系统发送组合键,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在ubuntu18.04下,通过编程向系统发送组合键
实现原理:
在ubuntu,模拟发送组合键,本文的实现方式,是通过写文件的方式,来模拟键盘事件。在/dev/目录下,有一个“uinput”字符设备文件,我们可以写此文件,来模拟键盘事件。
向“uinput”文件写一个按钮,则是单键按下,连续写多个按钮,则可以模拟组合键。
源码:
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
static void sendCtrl_Alt_Del_Key()
{int uinp_fd = open("/dev/uinput",O_RDWR);if (uinp_fd < 0){//qDebug()<<"unable to open /dev/uinput";return;}if(ioctl(uinp_fd ,UI_SET_EVBIT,EV_KEY)<0) //设置设备所支持的动作,#defineEV_KEY 0x01 // 按下键{//qDebug()<<"unable to set EV_KEY";return;}if(ioctl(uinp_fd ,UI_SET_EVBIT,EV_REP)<0) //设置设备所支持的动作,#defineEV_KEY 0x02 // 释放{//qDebug()<<"unable to set EV_REP";return;}for(int i = 0; i < 256; i++){ //---------------------???????ioctl(uinp_fd , UI_SET_KEYBIT, i);}//创建设备并写入至input子系统struct uinput_user_dev uinput;memset(&uinput,0,sizeof(uinput));uinput.id.version = 4;uinput.id.bustype = BUS_USB;strncpy(uinput.name,"virtual device a",UINPUT_MAX_NAME_SIZE);int ret = write( uinp_fd , &uinput, sizeof(uinput) );if(ret<0){//qDebug()<<"unable to write(uinp_fd , &uinput, sizeof(uinput)";return;}int err = ioctl(uinp_fd, UI_DEV_CREATE);if(err < 0){//qDebug()<<"unable to creat device";return;}//construct input_event and send itstruct input_event event;unsigned int key_code = KEY_LEFTCTRL; //键值usleep(100000);//importan//unsigned int key_code = KEY_CAPSLOCK;event.type = EV_KEY;event.code = key_code;event.value = 1; //1 means pressed signalgettimeofday(&event.time, NULL);if (write(uinp_fd, &event, sizeof(event)) < 0) {//qDebug()<<"unable to write key event";return;}event.code = KEY_LEFTALT;if (write(uinp_fd, &event, sizeof(event)) < 0) {//qDebug()<<"unable to write key event";return;}event.code = KEY_DELETE;if (write(uinp_fd, &event, sizeof(event)) < 0) {//qDebug()<<"unable to write key event";return;}gettimeofday(&event.time, NULL);event.value = 0;// send sync signal///event.type = EV_SYN;event.code = SYN_REPORT;event.value = 0;gettimeofday(&event.time, NULL);if( write(uinp_fd, &event, sizeof(event))<0 )//发送同步信号{//qDebug()<<"unable to write sync event";return;}close(uinp_fd);
}
这篇关于在ubuntu18.04下,通过编程向系统发送组合键的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!