如何以编程方式将键事件发送到Java App中的任何窗口/进程? [英] How to programmatically send a key event to any window/process in a Java App?
问题描述
使用Java应用程序,如何以编程方式将键事件(字母,数字,标点符号,箭头等)发送/触发到同一台机器上的窗口/进程?
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?
推荐答案
假设您知道该窗口的位置,您可以使用 java.awt.Robot
Assuming you know a position that window will be you could use java.awt.Robot
这在屏幕上覆盖10,50的任何窗口中键入a。
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);
如果您有一个窗口,您知道在10,400处覆盖10,50,另一个在400,400然后这将在不同的窗口中键入xy和z。在我的测试中,我还需要一些延迟才能使其更可靠。
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);
这篇关于如何以编程方式将键事件发送到Java App中的任何窗口/进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!