Search code examples
pythonwinapipywin32

win32gui shows some windows, that are not open


I'm using the win32gui package for the first time. I found the following examples to printout all opened windows.

But I am wondering about that the log_app_list() function contains windows, that are not opened. For example 'Microsoft Store' and 'Einstellungen' (means settings in german). Can someone explain me this unexpected behavior?

import win32gui

def window_enum_handler(hwnd, resultList):
    if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '':
        resultList.append((hwnd, win32gui.GetWindowText(hwnd)))

def get_app_list(handles=[]):
    mlst=[]
    win32gui.EnumWindows(window_enum_handler, handles)
    for handle in handles:
        mlst.append(handle)
    return mlst

def log_app_list():
    appwindows = get_app_list()
    for i in appwindows:
        print(i)

log_app_list()

Solution

  • It depends on the state of the process in the background, these windows are not "unopened", but the process is in the suspended state, you can check in the task manager, and The process "WinStore.App.exe" and "SystemSettings.exe" is in Suspended status: enter image description here

    You could use DwmGetWindowAttribute with DWMWA_CLOAKED to get its cloaked property, to exclude them:

    import win32gui
    import ctypes
    from ctypes import c_int
    import ctypes.wintypes
    from ctypes.wintypes import HWND, DWORD
    dwmapi = ctypes.WinDLL("dwmapi")
    DWMWA_CLOAKED = 14 
    isCloacked = c_int(0)
    def window_enum_handler(hwnd, resultList):
        if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '':
            dwmapi.DwmGetWindowAttribute(HWND(hwnd), DWORD(DWMWA_CLOAKED), ctypes.byref(isCloacked), ctypes.sizeof(isCloacked))
            if(isCloacked.value == 0):
                resultList.append((hwnd, win32gui.GetWindowText(hwnd)))
    
    def get_app_list(handles=[]):
        mlst=[]
        win32gui.EnumWindows(window_enum_handler, handles)
        for handle in handles:
            mlst.append(handle)
        return mlst
    
    def log_app_list():
        appwindows = get_app_list()
        for i in appwindows:
            print(i)
    
    log_app_list()