I asked a similar question on a previous thread (https://stackoverflow.com/questions/5206633/java-find-out-what-application-window-is-in-focus) but I was guided to use JNI, and I'm not having much success with it... I've read some tutorials and while some work fine, others don't I still can't get the information I need, which is the title of the window on the foreground.
Now I'm looking into JNA but I can't figure out how to access GetForegroundWindow() ... I think I can print the text once I get the handle to the window using this code (found on another thread):
import com.sun.jna.*;
import com.sun.jna.win32.*;
public class jnatest {
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount);
}
public static void main(){
byte[] windowText = new byte[512];
PointerType hwnd = //GetForegroundWindow() (?)...
User32.INSTANCE.GetWindowTextA(hwnd, windowText, 512);
System.out.println(Native.toString(windowText));
}
}
Any suggestions? Thanks!
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));
}
}