Getting active window information in Java

Viewed 25772

I am trying to upgrade my application in Java to work only if a window of process with certain name is active. I have found out that this is possible by using JNI, but I have no idea how exactly to do that. I just could not find any description or example that would explain it. My question is - how to get process name of currently active window in Windows (via JNI, or anything else - I accept any another solution)?

3 Answers

Simply

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.StdCallLibrary;

public class WinSysUser32HWND {
    public interface User32 extends StdCallLibrary {
        User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
        HWND GetForegroundWindow();
        void GetWindowTextW(HWND hWnd, char[] lpString, int nMaxCount);
    }

    public static void main(String[] args) {
        char[] buffer = new char[1024 * 2];
        User32.INSTANCE.GetWindowTextW(User32.INSTANCE.GetForegroundWindow(), buffer, 1024);
        System.out.println("Active window title: " + Native.toString(buffer));
    }
}
Related