How to programmatically send a key event to any wi

2019-05-30 13:36发布

问题:

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?

回答1:

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);