从当前流程获取hWnd

时间:2013-10-23 17:18:58

标签: java winapi jna

我尝试使用 GetCurrentProcess 函数从当前进程获取hWnd来显示每个进程的路径。但是我在这一行中遇到了错误:User32.INSTANCE.GetWindowThreadProcessId(hWnd, pid); 如何将其转换为所需的类型?

  

User32类型中的方法GetWindowThreadProcessId(WinDef.HWND,IntByReference)不适用于参数(WinNT.HANDLE,IntByReference)

有我的代码:

try {
    while (kernel32.Process32Next(snapshot, processEntry)) {
        kernel32.GetCurrentProcess();
        HANDLE hWnd = kernel32.GetCurrentProcess();
        User32.INSTANCE.GetWindowThreadProcessId(hWnd, pid);

        HANDLE process = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0010,
                false, pid.getValue());
        psapi.GetModuleFileNameExA(process, null, path, 1024);

        System.out.println(Native.toString(path));
    }
} finally {
    kernel32.CloseHandle(snapshot);
}

UPD: 问题以这种方式解决了:

try {
    while (kernel32.Process32Next(snapshot, processEntry)) {

        HANDLE process = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0010,
                false, processEntry.th32ProcessID.intValue());
        if (process != null) {
            int len = psapi.GetModuleFileNameExW(process, null, path,
                    1024);
            if (len > 0) {
                System.out.println(new String(path, 0, len));
            } else {
                System.out.println("GetModuleFileNameW failed");
            }
        } else {
            System.out.println(kernel32.GetLastError());
        }
        System.out.println(process != null ? Native.toString(path) : "error");
    }
} finally {
    kernel32.CloseHandle(snapshot);
}

谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

A)使用Win32 API EnumProcesses或Win32 API CreateToolhelp32Snapshot / Process32First / {{3}获取进程标识符(PID)列表} / Process32Next

对于每个PID,

B),使用win32 API CloseHandle获取进程的HANDLE(请求PROCESS_QUERY_INFORMATION为dwDesiredAccess)。使用该句柄,使用Win32 API OpenProcess(并且不要忘记使用CloseHandle关闭HANDLE)

希望这有帮助(因为那不是JAVA代码,对不起)