import ctypes
import sys
from ctypes import wintypes
import psutil

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)

print("Listing all processes with windows:")
def cb(h, l):
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
    length = user32.GetWindowTextLengthW(h)
    if length > 0:
        buf = ctypes.create_unicode_buffer(length + 1)
        user32.GetWindowTextW(h, buf, length + 1)
        try:
            pname = psutil.Process(pid.value).name()
        except Exception:
            pname = "unknown"
        if user32.IsWindowVisible(h):
            print(f"HWND: 0x{h:X} | PID: {pid.value:<6} | Proc: {pname:<15} | Title: {buf.value}")
    return True

ENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows(ENUMPROC(cb), 0)
