Skip to content

Instantly share code, notes, and snippets.

@vladholubiev
Created June 30, 2014 22:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vladholubiev/0a48c041d3ffed69fb6f to your computer and use it in GitHub Desktop.
Save vladholubiev/0a48c041d3ffed69fb6f to your computer and use it in GitHub Desktop.
Get current active windows title and process using JNA
import static enumeration.EnumerateWindows.Kernel32.*;
import static enumeration.EnumerateWindows.Psapi.*;
import static enumeration.EnumerateWindows.User32DLL.*;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.ptr.PointerByReference;
public class EnumerateWindows {
private static final int MAX_TITLE_LENGTH = 1024;
public static void main(String[] args) throws Exception {
char[] buffer = new char[MAX_TITLE_LENGTH * 2];
GetWindowTextW(GetForegroundWindow(), buffer, MAX_TITLE_LENGTH);
System.out.println("Active window title: " + Native.toString(buffer));
PointerByReference pointer = new PointerByReference();
GetWindowThreadProcessId(GetForegroundWindow(), pointer);
Pointer process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pointer.getValue());
GetModuleBaseNameW(process, null, buffer, MAX_TITLE_LENGTH);
System.out.println("Active window process: " + Native.toString(buffer));
}
static class Psapi {
static { Native.register("psapi"); }
public static native int GetModuleBaseNameW(Pointer hProcess, Pointer hmodule, char[] lpBaseName, int size);
}
static class Kernel32 {
static { Native.register("kernel32"); }
public static int PROCESS_QUERY_INFORMATION = 0x0400;
public static int PROCESS_VM_READ = 0x0010;
public static native int GetLastError();
public static native Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, Pointer pointer);
}
static class User32DLL {
static { Native.register("user32"); }
public static native int GetWindowThreadProcessId(HWND hWnd, PointerByReference pref);
public static native HWND GetForegroundWindow();
public static native int GetWindowTextW(HWND hWnd, char[] lpString, int nMaxCount);
}
}
@amitrathi1982
Copy link

can anybody please guide how do we use this to get active windows as confusion is the file name is "getActiveWindow.java" but in code class name is different.

@NecroMancer05
Copy link

instal jna than cpoy all codes to your class than use it .

@debabratahazra
Copy link

This java class is incomplete. Lots of methods are not yet defined in this class. How to solve all these undefined methods here?

@goias5
Copy link

goias5 commented Apr 26, 2019

I had a problem, there is exceptions, erros, it show the active window but then crashes. How to show all opne windows, not only the main one?
Anyway it worked to show only 1 window, so it deserved a star.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment