Java 如何以编程方式生成按键事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18169598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I programmatically generate keypress events?
提问by Anubha
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.
java程序应该做的是它应该在没有人按下键盘键的情况下触发键盘按下。因此,任何需要键盘输入的在 Windows 中运行并获得焦点的程序都将在没有人实际按下键盘的情况下获得输入。
I found these related questions here : question 1, question 2
I was wondering if there is any method to do this in Java.
我想知道在 Java 中是否有任何方法可以做到这一点。
回答by Doorknob
Use the Robotclass.
使用机器人类。
Code snippet:
代码片段:
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);
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.
但是,如果您尝试在计算机上自动执行任务,我会推荐AutoHotKey。它致力于自动化常见任务,因此使用它而不是 Java 会更容易。