Using JNA to get GetForegroundWindow(); Using JNA to get GetForegroundWindow(); windows windows

Using JNA to get GetForegroundWindow();


How about simply adding a method call to match the native GetForegroundWindow to your interface, something like so:

import com.sun.jna.*;import com.sun.jna.platform.win32.WinDef.HWND;import com.sun.jna.win32.*;public class JnaTest {   public interface User32 extends StdCallLibrary {      User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);      HWND GetForegroundWindow();  // add this      int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount);   }   public static void main(String[] args) throws InterruptedException {      byte[] windowText = new byte[512];      PointerType hwnd = User32.INSTANCE.GetForegroundWindow(); // then you can call it!      User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512);      System.out.println(Native.toString(windowText));   }}


If getting the window title is all you want to do, you don't have to explicitlyload the user32 library. JNA comes with it, in the platform.jar file (atleast in v3.4 it does).

I got this working here:

import com.sun.jna.Native;import com.sun.jna.platform.win32.WinDef.HWND;import com.sun.jna.platform.win32.User32;public class JnaApp {    public static void main(String[] args) {        System.out.println("title is " + getActiveWindowTitle());    }    private static String getActiveWindowTitle() {        HWND fgWindow = User32.INSTANCE.GetForegroundWindow();        int titleLength = User32.INSTANCE.GetWindowTextLength(fgWindow) + 1;        char[] title = new char[titleLength];        User32.INSTANCE.GetWindowText(fgWindow, title, titleLength);        return Native.toString(title);    }}

See more on User32's Javadoc. Its got almost all the functions in the user32 library.