【问题标题】:Java Robot Class - Add focus to a specific running Application?Java 机器人类 - 将焦点添加到特定正在运行的应用程序?
【发布时间】:2012-06-07 00:41:22
【问题描述】:

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

谢谢!

【问题讨论】:

  • Robot 类会将字符输入到任何具有焦点的应用程序中。如果您希望 Alt+Tab 进入 Word,它也可以这样做。所以,你在正确的轨道上。

标签: java awtrobot


【解决方案1】:

机器人无法自动执行此操作。您可以按照上面的建议通过 alt-tab 激活另一个应用程序,但您需要知道要激活的应用程序的 z 顺序。我认为要真正做到最好,您需要获取要激活的顶级窗口的窗口句柄 (hWnd)(如果这是 Windows 应用程序),然后使用 Windows user32 库函数激活所需的窗口。为此,我建议使用 JNA 作为最简单的方法之一(与 JNI 相比)。您必须首先下载 JNA jna.jar 和 platform.jar jar 文件,并将它们放在您的类路径中,然后您就可以轻松调用大多数操作系统方法。例如,我刚刚为 Windows 应用程序启动并运行了这种东西,我可以根据窗口名称(完整或部分)获取正在运行的顶级 Windows 应用程序的 hWnd,然后使用该 hWnd,调用 user32's setForegroundWindow 函数。如果您想激活 Windows 应用程序并想进一步追求这一点,请对此答案发表评论,我可以向您展示我为此拥有的代码。如果是这样,您将需要更详细地了解您正在尝试做的事情。

祝你好运!

【讨论】:

    【解决方案2】:

    对于我刚才在 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

    【讨论】:

      【解决方案3】:

      您没有指定系统,在 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);
      

      【讨论】:

        猜你喜欢
        • 2022-12-12
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 1970-01-01
        相关资源
        最近更新 更多