如何以编程方式生成按键事件?

2022-01-13 00:00:00 keyboard system java awtrobot awt

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.

相关文章