Java Robot Class – 将焦点添加到特定的运行应用程序?

我只想弄清楚是否/如何让Java Robot类将焦点从正在运行的java应用程序更改为特定进程,例如ms word或firefox。

谢谢!

机器人不能自动完成。 您可以通过alt-tab激活另一个应用程序,如上所述,但您需要知道要激活的应用程序的z顺序。 我认为要真正做到最好,你需要获得要激活的顶级窗口的窗口句柄(hWnd)(如果这是一个Windows应用程序),然后使用Windows user32库函数激活想要的窗口。 为此,我建议使用JNA作为最简单的方法之一(与JNI相比)。 您必须首先下载JNA jna.jar和platform.jar jar文件,并将它们放在类路径上,然后您可以轻松调用大多数OS方法。 例如,我已经为Windows应用程序运行了这样的东西,我可以根据窗口名称(完整或部分)获取运行的顶级Windows应用程序的hWnd,然后使用该hWnd,调用user32的setForegroundWindow函数。 如果您想要激活Windows应用程序并希望进一步追求,请回答此问题,我可以向您展示我的代码。 如果是这样,您将需要详细了解您正在尝试做什么。

祝你好运!

对于Google中我遇到的任何问题:

public class activate { public interface User32 extends W32APIOptions { User32 instance = (User32) Native.loadLibrary("user32", User32.class, DEFAULT_OPTIONS); boolean ShowWindow(HWND hWnd, int nCmdShow); boolean SetForegroundWindow(HWND hWnd); HWND FindWindow(String winClass, String title); int SW_SHOW = 1; } public static void main(String[] args) { User32 user32 = User32.instance; HWND hWnd = user32.FindWindow(null, "Downloads"); // Sets focus to my opened 'Downloads' folder user32.ShowWindow(hWnd, User32.SW_SHOW); user32.SetForegroundWindow(hWnd); } } 

图片来源: http : //www.coderanch.com/t/562454/java/java/FindWindow-ShowWindow-SetForegroundWindow-effect-win

您没有在Mac上指定系统,可以使用AppleScript执行此操作。 AppleScript已集成到系统中,因此它将始终可用。 https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html

您只需要检测到您在Mac上并且具有应用程序的名称。

 Runtime runtime = Runtime.getRuntime(); String[] args = { "osascript", "-e", "tell app \"Chrome\" to activate" }; Process process = runtime.exec(args);