How can I programmatically generate keypress events? [duplicate]

社会主义新天地 提交于 2019-11-26 23:15:06

问题


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.

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

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


回答1:


Use the Robot class.

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.



来源:https://stackoverflow.com/questions/18169598/how-can-i-programmatically-generate-keypress-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!