Linux模拟按键输入

本文介绍了一种在Linux环境下通过向特定设备文件写入数据来模拟键盘按键的方法,并提供了一个简单的C语言程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Linux应用层,可以往/dev/input/event...写入数据来模拟按键输入,程序如下:

#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>

/*
struct input_event {
	struct timeval time;
	__u16 type;
	__u16 code;
	__s32 value;
};

#define EV_KEY                  0x01
*/
int reportkey(int fd, uint16_t type, uint16_t keycode, int32_t value)
{
	struct input_event event;

	event.type = type;
	event.code = keycode;
	event.value = value;

	gettimeofday(&event.time, 0);

	if (write(fd, &event, sizeof(struct input_event)) < 0) {
		printf("report key error!\n");
		return -1;
	}

	return 0;
}

#define DEVNAME "/dev/input/event4"

#define KEYDOWN	1
#define KEYUP	0

int main(int argc, char *argv[])
{
	uint16_t keycode;

	int k_fd;

	k_fd = open(DEVNAME, O_RDWR);

	if (k_fd < 0) {
		printf("open error!\n");
		return k_fd;
	}

	keycode = KEY_A;
	reportkey(k_fd, EV_KEY, keycode, KEYDOWN);
	reportkey(k_fd, EV_KEY, keycode, KEYUP);

	close(k_fd);

	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值