Home > OS >  Python Get windowtitle from Process ID or Process Name
Python Get windowtitle from Process ID or Process Name

Time:01-11

I want to get the Windowtitle of a specific process (e.g. Spotify.exe).

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

I tried multiple different versions I found on the internet, but most solutions where for the active window, but in my case it is nit always the active window, so I have to go by process name or process id.

So, basically I'm searching for something like this

title = getTitleFromProcessName('Spotify.exe')

and then title is the corresponding window title of the spotify window.

CodePudding user response:

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()

I solved it using this piece of code With this I get the window handle of the qobuz window if it's open, else it's none

  •  Tags:  
  • Related