0

我有一个窗口的窗口句柄。我需要获取有关进程的其他信息,例如 CPU%、内存名称等。

我怎么才能得到它?

4

1 回答 1

1

考虑使用Java Native Access从这里下载 jna.jar 和 platform.jar 。

您可能已经注意到,我们可以在user32.dll中使用GetWindowThreadProcessId从窗口句柄中获取 pid。然后我们可以使用kernel32.dll中的OpenProcess来获取指向该进程的指针。然后psapi.dll中的GetProcessMemoryInfoGetModuleBaseNameAPI可以帮助您从该进程对象中获取进程信息,并且kernel32.dll中的GetProcessTimes可以返回 cpu 使用情况。包含一个名为PROCESS_MEMORY_COUNTERS的结构,需要JNA中的结构来处理。GetProcessMemoryInfo

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));
于 2013-06-12T09:16:51.583 回答