如何通过可执行文件路径或名称获取窗口句柄(hwnd)?

问题描述 投票:0回答:2

有没有办法通过仅提供可执行路径或名称来从特定窗口获取 hwnd 对象?

类似于

GetForegroundWindow()
中的
win32gui
,但不仅仅是前景窗口。

我想象这样的事情:

GetWindowByPath("C:/mypath/Spotify.exe")
GetWindowByName("Spotify")
。也许与ahk? (我对AHK一无所知)

我现在已经阅读了其他问题和文档几个小时,但还没有找到方法。 预先感谢:)

python windows pywin32 hwnd
2个回答
0
投票

没有直接的方法,你需要从两端接近它并在中间相遇,这就是进程id。

如果这是本机代码,您可以使用 Toolhelp 函数枚举所有进程并查看每个进程的文件名。当您找到匹配项时,请记住进程 ID。

然后你可以调用

EnumWindows
来查找所有顶级窗口。在回调中,您将在每个窗口上调用
GetWindowThreadProcessId
,直到找到与您之前找到的进程 ID 相匹配的窗口。


0
投票

这里是一个示例代码,用于在给出 exe 路径时获取

hwnd
列表。

import win32gui
import win32process
import psutil

def GetHwndByPath(path):
    hwnd_list = []

    def winEnumHandler(hwnd, ctx):
        if win32gui.IsWindowVisible(hwnd):
            thread_id, process_id = win32process.GetWindowThreadProcessId(hwnd)
            # Get the process name and executable path
            process = psutil.Process(process_id)
            process_name = process.name()
            process_path = process.exe()
            if process_path == path:
                hwnd_list.append(hwnd)

    win32gui.EnumWindows(winEnumHandler, None)
    return hwnd_list

示例用法和输出:

print(GetHwndByPath("C:\Program Files\DAUM\PotPlayer\PotPlayerMini64.exe"))

# output:
[24389654, 27541266, 22546206]

然后你可以使用 hwnds 来做你想做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.