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

Loc*_*kna 1 python windows winapi window

我想获取特定进程的Windowtitle(例如Spotify.exe)。

def winEnumHandler( hwnd, ctx ):
    if win32gui.IsWindowVisible( hwnd ):
        print (hex(hwnd), win32gui.GetWindowText( hwnd ))
Run Code Online (Sandbox Code Playgroud)

我尝试了在互联网上找到的多个不同版本,但大多数解决方案都针对活动窗口,但在我的情况下,它始终是活动窗口,所以我必须按进程名称或进程 ID 进行操作。

所以,基本上我正在寻找这样的东西

title = getTitleFromProcessName('Spotify.exe')
Run Code Online (Sandbox Code Playgroud)

然后 title 是 Spotify 窗口对应的窗口标题。

Loc*_*kna 5

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()
Run Code Online (Sandbox Code Playgroud)

我使用这段代码解决了这个问题有了这个,我得到了 qobuz 窗口的窗口句柄(如果它是打开的),否则它就没有