How to programmatically send a key event to any window/process in a Java App?

我们两清 提交于 2019-12-10 11:34:24

问题


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


来源:https://stackoverflow.com/questions/32641269/how-to-programmatically-send-a-key-event-to-any-window-process-in-a-java-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!