如何以编程方式生成按键事件? [英] How can I programmatically generate keypress events?

查看:18
本文介绍了如何以编程方式生成按键事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java 程序应该做的是它应该在某些情况下触发键盘按下,而无需人按下键盘键.因此,任何在 windows 中运行且需要键盘输入的程序都可以在没有人实际按下键盘的情况下获得输入.

What the java program should do is it should trigger keyboard press on some condition without a person pressing a keyboard key. So any program running in windows and in focus which requires keyboard input will get the input without a person actually pressing the keyboard.

我在这里找到了这些相关问题:问题1问题2

I found these related questions here : question 1, question 2

我想知道在 Java 中是否有任何方法可以做到这一点.

I was wondering if there is any method to do this in Java.

推荐答案

使用 机器人 类.

代码片段:

import java.awt.Robot;
import java.awt.KeyEvent;

Robot r = new Robot();
int keyCode = KeyEvent.VK_A; // the A key
r.keyPress(keyCode);
// later...
r.keyRelease(keyCode);

但是,如果您尝试在计算机上自动执行一项任务,我建议您使用 AutoHotKey.它致力于自动化常见任务,因此使用它而不是 Java 会更容易.

However, if you are trying to automate a task on your computer, I would recommend AutoHotKey. It's dedicated to automating common tasks, so it would be easier to use it instead of Java.

这篇关于如何以编程方式生成按键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆