【问题标题】:Python Get windowtitle from Process ID or Process NamePython从进程ID或进程名称获取windowtitle
【发布时间】:2022-01-07 09:13:39
【问题描述】:

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

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

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

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

title = getTitleFromProcessName('Spotify.exe')

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

【问题讨论】:

  • 进程没有名字。如果要枚举给定特定进程 ID 的进程拥有的窗口,您将如何确定进程 ID?无论如何,如果你想过滤进程 ID,你可以在你的枚举回调中调用GetWindowThreadProcessId
  • 您可以使用GetAncestor 获取所有顶级窗口的列表,并使用GetWindowThreadProcessId 查看这些窗口的PID。它不是很可靠,但它确实有效。我想我已经回答了同样的问题,但我找不到答案。
  • @vii 您不能用GetAncestor 枚举所有顶级窗口。您使用 OP 已经在使用的 EnumWindows 枚举所有顶级窗口。
  • @IInspectable,是的,我的错误。使用EnumWindows 枚举并使用GetAncestor 检查窗口是否位于顶层。
  • @vii EnumWindows 仅枚举顶级窗口。您不必检查它是否是顶级窗口。

标签: python windows winapi window


【解决方案1】:
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 窗口的窗口句柄,如果它是打开的,否则它没有

【讨论】:

  • 很好的答案,对理解问题很有帮助
猜你喜欢
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 2022-01-12
相关资源
最近更新 更多