icespace
icespace

Reputation: 501

Active other process's window in Java

I have two Java swing applications (means running in two JVM). Is there any way to switch between them? Active another application's window by Java code?

Upvotes: 3

Views: 3264

Answers (1)

Xeon
Xeon

Reputation: 5989

You can try using JNA. I'll give you some code for Windows (more or less will be for other systems) using Maven: (sorry but I cannot get formatting right)

  1. Create Maven project, and add dependencies:

    <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. Create interface

    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. Create class

    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. And invoke

    User32.INSTANCE.SetFocus(Win32WindowUtils.GetWindowHandle(windowTitle.toUpperCase(), null);
    

Of course - windowTitle is your window title (String) that you want to focus.

Upvotes: 3

Related Questions