Control your keyboard with Java
You may control your keyboard using this simple program.Please dont run this program directly, its just for reference
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Anurag
*/
public class ControlKeyboard {
public static void main(String args[]) {
new ControlKeyboard().control_keyboard();
}
public void control_keyboard() {
try {
Robot robot = new Robot();
//Perform ALT+TAB which will switch your window
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_TAB);
Thread.sleep(100);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_TAB);
//Press Key A
robot.keyPress(KeyEvent.VK_A);
Thread.sleep(100);
robot.keyRelease(KeyEvent.VK_A);
//Similarly to press key Z use
robot.keyPress(KeyEvent.VK_Z);
Thread.sleep(100);
robot.keyRelease(KeyEvent.VK_Z);
//Press ALT key
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(100);
robot.keyRelease(KeyEvent.VK_ALT);
//Press Control Key
robot.keyPress(KeyEvent.VK_CONTROL);
Thread.sleep(100);
robot.keyRelease(KeyEvent.VK_CONTROL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explaination :
First we make an object of Robot class.
If we want to press a keyboard key then we use the keyPress and keyRelease method.
Always make sure there is a delay of some small seconds before key press and key release events
Suppose if we want to click A then we use KeyEvent.VK_A, for B we use VK_B ...., for Z VK_Z.
To perform Control key use VK_CONTROL, ALT key we use VK_ALT and likewise there are other combinations.
To perform multiple key event we perform the key press for both keys and after that give a small delay. After that we perform the release operation.
For eg: In above example we perform keypress for both VK_ALT and VK_TAB together. Then we give small delay and then perform the keyrelease for VK_ALT and VK_TAB together
0 comments:
Post a Comment