模拟在 Java 中按下的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/784414/
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
Simulate a key held down in Java
提问by Ross
I'm looking to simulate the action of holding a keyboard key down for a short period of time in Java. I would expect the following code to hold down the A key for 5 seconds, but it only presses it once (produces a single 'a', when testing in Notepad). Any idea if I need to use something else, or if I'm just using the awt.Robot class wrong here?
我希望模拟在 Java 中短时间按住键盘键的动作。我希望下面的代码按住 A 键 5 秒钟,但它只按下一次(在记事本中测试时会产生一个“a”)。知道我是否需要使用其他东西,或者我只是在这里错误地使用了 awt.Robot 类?
Robot robot = null;
robot = new Robot();
robot.keyPress(KeyEvent.VK_A);
Thread.sleep(5000);
robot.keyRelease(KeyEvent.VK_A);
回答by edwardsmatt
Thread.sleep() stops the current thread (the thread that is holding down the key) from executing.
Thread.sleep() 停止当前线程(按住键的线程)执行。
If you want it to hold the key down for a given amount of time, maybe you should run it in a parallel Thread.
如果您希望它在给定的时间内按住键,也许您应该在并行线程中运行它。
Here is a suggestion that will get around the Thread.sleep() issue (uses the command pattern so you can create other commands and swap them in and out at will):
这是一个可以解决 Thread.sleep() 问题的建议(使用命令模式,因此您可以创建其他命令并随意交换它们):
public class Main {
public static void main(String[] args) throws InterruptedException {
final RobotCommand pressAKeyCommand = new PressAKeyCommand();
Thread t = new Thread(new Runnable() {
public void run() {
pressAKeyCommand.execute();
}
});
t.start();
Thread.sleep(5000);
pressAKeyCommand.stop();
}
}
class PressAKeyCommand implements RobotCommand {
private volatile boolean isContinue = true;
public void execute() {
try {
Robot robot = new Robot();
while (isContinue) {
robot.keyPress(KeyEvent.VK_A);
}
robot.keyRelease(KeyEvent.VK_A);
} catch (AWTException ex) {
// Do something with Exception
}
}
public void stop() {
isContinue = false;
}
}
interface RobotCommand {
void execute();
void stop();
}
回答by OscarRyz
Just keep pressing?
就一直按吗?
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class PressAndHold {
public static void main( String [] args ) throws Exception {
Robot robot = new Robot();
for( int i = 0 ; i < 10; i++ ) {
robot.keyPress( KeyEvent.VK_A );
}
}
}
I think the answer provided by edward will do!!
我认为爱德华提供的答案会做!!
回答by TwentyMiles
There is no keyDown event in java.lang.Robot. I tried this on my computer (testing on a console under linux instead of with notepad) and it worked, producing a string of a's. Perhaps this is just a problem with NotePad?
java.lang.Robot 中没有 keyDown 事件。我在我的电脑上试过这个(在 linux 下的控制台上测试而不是用记事本测试)并且它起作用了,产生了一个 a 的字符串。也许这只是记事本的问题?

