Ravi Kumar Gupta
Ravi Kumar Gupta

Reputation: 1798

How to get process information from windowHandle in Native with Java?

I have windowHandle of a window. I need to get other information about the process like CPU%, memory name etc.

How can I get it?

Upvotes: 0

Views: 1463

Answers (1)

StarPinkER
StarPinkER

Reputation: 14281

Considering use Java Native Access. Download jna.jar and platform.jar from here.

You may have noticed that we can use GetWindowThreadProcessId in user32.dll to get the pid from a window handle. Then we can use OpenProcess in kernel32.dll to get a pointer to that process. Then the bunch of APIs like GetProcessMemoryInfo and GetModuleBaseName in psapi.dll can help you to get process information from that process object and the GetProcessTimes in kernel32.dll can return cpu usage. The GetProcessMemoryInfo contains a structure named PROCESS_MEMORY_COUNTERS which needs Structure in JNA to handle.

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);
    public static native boolean GetProcessTimes(Pointer hProcess, int lpCreationTime,int LPFILETIME lpExitTime, int lpKernelTime, int lpUserTime
}

static class Psapi {
    static { Native.register("psapi"); }
    public static native int GetModuleBaseNameW(Pointer hProcess, Pointer hmodule, char[] lpBaseName, int size);
    ...
}

static class User32DLL {
    static { Native.register("user32"); }
    public static native int GetWindowThreadProcessId(HWND hWnd, PointerByReference pref);
    public static native int GetWindowTextW(HWND hWnd, char[] lpString, int nMaxCount);
}

PointerByReference pointer = new PointerByReference();
GetWindowThreadProcessId(yourHandle, 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));

Upvotes: 2

Related Questions