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的时候 会看到耗时特别久, 对于分析按键触发的性能事件有很大的干扰!

相关推荐
tan77º6 分钟前
【Linux网络编程】网络基础
linux·服务器·网络
还鮟18 分钟前
CTF Web的数组巧用
android
shaun200119 分钟前
华为c编程规范
c语言
MeshddY43 分钟前
(超详细)数据库项目初体验:使用C语言连接数据库完成短地址服务(本地运行版)
c语言·数据库·单片机
笑衬人心。1 小时前
Ubuntu 22.04 + MySQL 8 无密码登录问题与 root 密码重置指南
linux·mysql·ubuntu
森焱森1 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机
小蜜蜂嗡嗡2 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
凌肖战2 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
aqi002 小时前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体
chanalbert2 小时前
CentOS系统新手指导手册
linux·运维·centos