在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 it
    struct 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 signal
    gettimeofday(&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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值