Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically generate keypress events? [duplicate]

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.

like image 395
Anubha Avatar asked Aug 11 '13 07:08

Anubha


1 Answers

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.

like image 157
tckmn Avatar answered Oct 21 '22 21:10

tckmn