Python 从进程 ID 或进程名称获取窗口标题

Python Get windowtitle from Process ID or Process Name

我想获取特定进程的窗口标题(例如Spotify.exe)。

def winEnumHandler( hwnd, ctx ):
    if win32gui.IsWindowVisible( hwnd ):
        print (hex(hwnd), win32gui.GetWindowText( hwnd ))

我尝试了在互联网上找到的多个不同版本,但大多数解决方案都适用于活动 window,但在我的情况下它总是活动 window,所以我必须去按进程名称或进程 ID。

所以,基本上我正在搜索类似这样的东西

title = getTitleFromProcessName('Spotify.exe')

然后title就是spotify对应的window标题window.

import win32gui
import win32process
import psutil
import ctypes

EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
IsWindowVisible = ctypes.windll.user32.IsWindowVisible

def getProcessIDByName():
    qobuz_pids = []
    process_name = "Qobuz.exe"

    for proc in psutil.process_iter():
        if process_name in proc.name():
            qobuz_pids.append(proc.pid)

    return qobuz_pids

def get_hwnds_for_pid(pid):
    def callback(hwnd, hwnds):
        #if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        _, found_pid = win32process.GetWindowThreadProcessId(hwnd)

        if found_pid == pid:
            hwnds.append(hwnd)
        return True
    hwnds = []
    win32gui.EnumWindows(callback, hwnds)
    return hwnds 

def getWindowTitleByHandle(hwnd):
    length = GetWindowTextLength(hwnd)
    buff = ctypes.create_unicode_buffer(length + 1)
    GetWindowText(hwnd, buff, length + 1)
    return buff.value

def getQobuzHandle():
    pids = getProcessIDByName()

    for i in pids:
        hwnds = get_hwnds_for_pid(i)
        for hwnd in hwnds:
            if IsWindowVisible(hwnd):
                return hwnd


if __name__ == '__main__':
    qobuz_handle = getQobuzHandle()

我用这段代码解决了 有了这个,我得到了 qobuz window 的 window 句柄,如果它是打开的,否则它是 none