C语言实现android/linux按键模拟

C语言实现 input事件模拟

c 复制代码
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>

int main() {
    int fd = open("/dev/input/event0", O_RDWR);
    if (fd < 0) {
        perror("Failed to open device");
        return -1;
    }

    // 定义 8 个输入事件(按顺序模拟按键按下和释放)
    struct input_event events[] = {
        // KEY_314 按下
        {.type = EV_KEY, .code = 314, .value = 1},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_212 按下
        {.type = EV_KEY, .code = 212, .value = 1},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_212 释放
        {.type = EV_KEY, .code = 212, .value = 0},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_314 释放
        {.type = EV_KEY, .code = 314, .value = 0},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0}
    };

    // 批量发送事件
    for (int i = 0; i < sizeof(events)/sizeof(events[0]); i++) {
        if (write(fd, &events[i], sizeof(struct input_event)) < 0) {
            perror("Failed to send event");
            close(fd);
            return -1;
        }
    }

    close(fd);
    return 0;
}

静态交叉编译

c 复制代码
aarch64-linux-gnu-gcc-10   123.c -o startup_camera_common --static

可以模拟 简单按键事件

为什么不用 shell命令

比如

adb shell "sendevent /dev/input/event0 0001 314 00000001"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 212 00000001"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 212 00000000"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 314 00000000"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

sendevent 是 busybox命令, 每次执行八条命令 耗时过长, 在抓 perfetto的时候 会看到耗时特别久, 对于分析按键触发的性能事件有很大的干扰!

相关推荐
Kratzdisteln1 天前
【linux】
linux·运维·服务器
阿豪只会阿巴1 天前
项目心得——发布者和订阅者问题解决思路
linux·开发语言·笔记·python·ubuntu·ros2
Elieal1 天前
常用的 Linux 命令
linux·运维·服务器
C.L.L1 天前
Linux中capslock+实现——input-remapper
linux
装不满的克莱因瓶1 天前
【2026最新 架构环境安装篇三】Docker安装RabbitMQ4.x详细教程
linux·运维·docker·容器·架构·rabbitmq
Hello_Embed1 天前
RS485 双串口通信 + LCD 实时显示(中断版)
c语言·笔记·单片机·学习·操作系统·嵌入式
音无八重1 天前
Linux(Ubuntu)下无法连接ppa.launchpadcontent.net的解决方法
linux·运维·ubuntu
超级大福宝1 天前
Vim 和 tmux 的常用注意事项
linux·编辑器·vim
xiaobobo33301 天前
c语言什么时候适合用三目运算什么时候适合用阶梯判断
c语言·三目运算·阶梯判断·花括号作用域
RisunJan1 天前
Linux命令-jwhois(查询域名和IP地址注册信息)
linux·tcp/ip