Java => shorten commands for the robot

Hey, using this piece of code:

try {

      Robot robot = new Robot();

      robot.keyPress(KeyEvent.VK_H);
      robot.keyRelease(KeyEvent.VK_H);
      robot.keyPress(KeyEvent.VK_A);
      robot.keyRelease(KeyEvent.VK_A);
      robot.keyPress(KeyEvent.VK_L);
      robot.keyRelease(KeyEvent.VK_L);
      robot.keyPress(KeyEvent.VK_L);
      robot.keyRelease(KeyEvent.VK_L);
      robot.keyPress(KeyEvent.VK_O);
      robot.keyRelease(KeyEvent.VK_O);

 } catch (AWTException e) {
      e.printStackTrace();
 }

I get this result:

hallo

But is there a way to shorten this process? for example something like:

try {

       Robot robot = new Robot();

       String  word = "hallo";

       // something like:
       robot.keyPress(KeyEvent.word);

   } catch (AWTException e) {
       e.printStackTrace();
   }

I know this example does not work, but I could not find documentation about it.

Do you have any ideas? greetings and thanks

+3
source share
2 answers

If you are using Java 7, you can use the method KeyEvent.getExtendedKeyCodeForCharto get the key code from char:

   import java.awt.event.KeyEvent; 

   [...]

   public static void type(Robot robot, String word) {
        for (int i = 0; i < word.length(); i++) {
            int keyCode = KeyEvent.getExtendedKeyCodeForChar(word.charAt(i));
            robot.keyPress(keyCode);
            robot.keyRelease(keyCode);
        }
    }

   [...]

   Robot robot = new Robot();
   type(robot, "hallo");
+4
source

Make such a method. Just use methods that take a character.

public void press(String s, Robot r)
{
    for (char ch : s.toCharArray())
    {
        if (Character.isUpperCase(ch))
            r.keyPress(KeyEvent.VK_SHIFT);

        r.keyPress(Character.toUpperCase(ch));
        r.keyRelease(Character.toUpperCase(ch));
    }
}

Or you can use this to get KeyCode.

KeyStroke.getKeyStroke(ch, 0).getKeyCode();

Or also

KeyEvent.getExtendedKeyCodeForChar(ch);

Hope this helps.

+1
source

All Articles