Java中如何通过windowHandle获取processId?线程如何关联processId?
在Java中通过Window Handle与Process ID互转的实现方法
一、通过Window Handle获取Process ID
你当前调用的User32.INSTANCE.GetWindowThreadProcessId本身就可以直接拿到Process ID,不需要额外做线程关联——这个方法的第二个参数是输出参数,专门用来接收进程ID。
你之前传null只获取了线程ID,修改代码即可同时拿到线程ID和对应的进程ID:
// 用IntByReference接收进程ID(JNA通过引用传递输出参数) IntByReference processId = new IntByReference(); // 调用方法时传入processId int threadId = User32.INSTANCE.GetWindowThreadProcessId(desktopWindow.getHWND(), processId); // 取出实际的进程ID值 int pid = processId.getValue();
这里的threadId就是你之前获取的线程ID,pid就是该线程所属的进程ID,二者天然关联。
二、通过Process ID获取Window Handle
反过来通过进程ID查找窗口句柄,需要遍历系统中所有顶层窗口,对每个窗口调用GetWindowThreadProcessId获取其所属进程ID,与目标PID匹配的就是对应窗口句柄。
用JNA的EnumWindows实现遍历:
// 目标进程ID int targetPid = 1234; // 存储找到的窗口句柄 AtomicReference<HWND> targetWindow = new AtomicReference<>(); User32.INSTANCE.EnumWindows((hwnd, data) -> { IntByReference pid = new IntByReference(); User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid); if (pid.getValue() == targetPid) { // 找到匹配窗口,保存句柄并终止遍历 targetWindow.set(hwnd); return false; } return true; }, null); // 结果窗口句柄,不为null则表示找到 HWND resultHwnd = targetWindow.get();
注意:一个进程可能对应多个窗口,上述代码仅返回第一个匹配的窗口;若需要收集所有关联窗口,可改用集合存储。
内容的提问来源于stack exchange,提问作者ameer zeya
相关产品推荐
相关产品推荐

