Java robot keyboard

2k views Asked by At

I am trying to make a application in Java, where you can control someones keyboard from a distance, but I am facing a problem. I thought something like this would be possible:

            //the message is the key input
            String[] parts = message.split("-");
            String KeyPressed = parts[1];//This is the key that's pressed(for example K)
                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_(KeyPressed));
                } catch (AWTException e1) {
            }

But this doesn't work. I know this one works, but you'll have to repeat it for every single key on your keyboard:

            //the message is the key input
            String[] parts = message.split("-");
            String KeyPressed = parts[1];
            if(KeyPressed.equals("H")){
                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_H);
                } catch (AWTException e1) {
                }
            }

Now my question is, what is the code to do all the keys in a few lines instead of doing the code above for every key on your keyboard?

3

There are 3 answers

2
Goran Štuc On BEST ANSWER

what you want to do is implement a KeyListener to receive all keys here is the event and some examples: KeyListener

1
Robin Green On

This will work for the letters A to Z:

robot.keyPress(KeyPressed);

But you'll have to use something else for some non-letter keys.


A problem is that you are receiving characters as input, but sending key codes as output. This is an unusual translation. It would be easier if you could somehow receive key codes and send them directly... see the answer from Goran for that!

Also, how are you even going to represent keys like Scroll Lock as a character?!

0
alex2410 On

Try to use KeyStroke for getting key code by String, like next :

KeyStroke keyStroke = KeyStroke.getKeyStroke("H");
try {
    Robot robot = new Robot();
    robot.keyPress(keyStroke.getKeyCode());
} catch (AWTException e) {
    e.printStackTrace();
}