在 Java 中模拟按下的键
我希望在 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);
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?
Robot robot = null;
robot = new Robot();
robot.keyPress(KeyEvent.VK_A);
Thread.sleep(5000);
robot.keyRelease(KeyEvent.VK_A);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Thread.sleep() 停止当前线程(按住该键的线程)的执行。
如果您希望它在给定的时间内按住按键,也许您应该在并行线程中运行它。
以下是解决 Thread.sleep() 问题的建议(使用命令模式,以便您可以创建其他命令并随意将它们换入换出):
Thread.sleep() stops the current thread (the thread that is holding down the key) from executing.
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):
一直按就可以吗?
我认为爱德华提供的答案就可以了!
Just keep pressing?
I think the answer provided by edward will do!!
java.lang.Robot 中没有 keyDown 事件。 我在我的电脑上尝试了这个(在Linux下的控制台上测试,而不是使用记事本)并且它有效,产生了一串a。 也许这只是记事本的问题?
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?