2

Using a Java app, how can I programmatically send/trigger a key event (letters,numbers,punctuation, arrows, etc) to a window/process on the same machine?

code
  • 5,294
  • 16
  • 62
  • 113

1 Answers1

5

Assuming you know a position that window will be you could use java.awt.Robot

This types a in whatever window is covering 10,50 on the screen.

Robot r = new Robot();
r.mouseMove(10, 50);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.keyPress(KeyEvent.VK_A);
r.keyRelease(KeyEvent.VK_A);

If you had one window you know to cover 10,50 another at 10,400 and another at 400, 400 then this would type x y and z in the different windows. In my testing I also needed some delays before moving to make it more reliable.

Robot r = new Robot();
r.mouseMove(10, 50);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_X);
r.keyRelease(KeyEvent.VK_X);
Thread.sleep(500);
r.mouseMove(10, 400);
Thread.sleep(500);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_Y);
r.keyRelease(KeyEvent.VK_Y);
Thread.sleep(500);
r.mouseMove(400, 400);
Thread.sleep(500);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.keyPress(KeyEvent.VK_Z);
r.keyRelease(KeyEvent.VK_Z);
WillShackleford
  • 6,918
  • 2
  • 17
  • 33
  • Thanks Will! This is helpful. – code Sep 17 '15 at 23:13
  • Lets say I have 3 windows open on my PC. I'm looking for a way to send key "x" to window #1, key "y" to window #2, and key "z" to window #3. – code Sep 17 '15 at 23:14
  • 2
    @android-user Assuming that the windows are not Java based (or in the same JVM), you will need a native implementation to find the windows and their positions, for [example](http://stackoverflow.com/questions/1173926/how-can-i-read-the-window-title-with-jni-or-jna), [example](http://stackoverflow.com/questions/8717999/how-to-get-list-of-all-window-handles-in-java-using-jna), [example](http://stackoverflow.com/questions/27839666/java-jna-find-partial-window-title) and [example](http://stackoverflow.com/questions/6391439/getting-active-window-information-in-java) – MadProgrammer Sep 17 '15 at 23:53