Java中的活动其他进程窗口

时间:2011-12-07 03:21:00

标签: java swing jvm

我有两个Java swing应用程序(意味着在两个JVM中运行)。有没有办法在它们之间切换?通过Java代码激活另一个应用程序的窗口?

1 个答案:

答案 0 :(得分:3)

您可以尝试使用JNA。我将使用Maven为您提供一些Windows代码(或多或少将用于其他系统): (抱歉,我无法正确格式化)

  1. 创建Maven项目,并添加依赖项:

    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>jna</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>net.java.dev.jna</groupId>
        <artifactId>platform</artifactId>
        <version>3.4.0</version>
    </dependency>
    
  2. 创建界面

    public interface User32 extends StdCallLibrary {
        User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, W32APIOptions.DEFAULT_OPTIONS);
        HWND GetParent(HWND hWnd);
        HWND FindWindow(String lpClassName, String lpWindowName);
        HWND SetFocus(HWND hWnd);
        HWND FindWindowEx(HWND hwndParent, HWND hwndChildAfter, String lpszClass, String lpszWindow);
        int GetWindowText(HWND hWnd, char[] lpString, int nMaxCount);
    }
    
  3. 创建课程

    public final class Win32WindowUtils {
        private static final int WIN_TITLE_MAX_SIZE = 512;
    
        public HWND GetWindowHandle(String strSearch, String strClass) {
            char[] lpString = new char[WIN_TITLE_MAX_SIZE];
            String strTitle;
            int iFind = -1;
            HWND hWnd = User32.INSTANCE.FindWindow(strClass, null);
            while(hWnd != null) {
                User32.INSTANCE.GetWindowText(hWnd, lpString, WIN_TITLE_MAX_SIZE);
                strTitle = new String(lpString);
                strTitle = strTitle.toUpperCase();
                iFind = strTitle.indexOf(strSearch);
                if(iFind != -1) {
                    return hWnd;
                }
                hWnd = User32.INSTANCE.FindWindowEx(null, hWnd, strClass, null);
            }
            return hWnd;
        }
    }
    
  4. 并调用

    User32.INSTANCE.SetFocus(Win32WindowUtils.GetWindowHandle(windowTitle.toUpperCase(), null);
    
  5. 当然 - windowTitle是您想要关注的窗口标题(String)。