在Java中模拟按键,以将用户输入内容写入另一个应用程序 [英] Simulate keypress in java to write user inputs to another application
问题描述
我正在开发一个虚拟键盘应用程序.一切工作正常,只不过我写的内容只写到当前应用程序中,而不是写在后面.
I am developing a virtual keyboard application. Everything works fine except that what ever i write is written into the present application only not the one that is running behind.
我之所以这样,是因为Java中的ROBOT类仅适用于创建它的应用程序上下文.
I fell this is because ROBOT class in java only works for the application context that creates it.
有没有解决的办法?
这是代码,我试图在我的Java应用程序后面的终端中写 ls :
Here is the code, i am trying to write ls in the terminal that is behind my java application:
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyPress('l');
robot.keyRelease('l');
robot.keyPress('s');
robot.keyRelease('s');
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
推荐答案
judging from this example, the Robot
class is able to send keystrokes to external applications - but they will arrive at the topmost window
so you basically need to focus the window to which you want to have your keystrokes sent, there seems to be a variety of solutions for this, im guessing this one is the easiest :
https://stackoverflow.com/a/4782350/351861 :
或者,您可以编写一个VBScript来激活另一个 应用.例如:
Alternatively, you can write a VBScript to activate another application. For example:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate("Firefox")
然后使用Java应用程序中的Runtime.exec执行脚本.
Then use Runtime.exec from your Java app to execute the script.
这篇关于在Java中模拟按键,以将用户输入内容写入另一个应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!