pythonwindowswinapiwin32gui

List all windows with win32gui


I'm trying to list all windows of Microsoft Windows 10 with Python and the win32gui module. The problem is that there are also processes listed that don't have a window in my understanding.

When I run this code with only Chrome and PyCharm open

import win32gui

def callback(hwnd, extra):
    if win32gui.IsWindowVisible(hwnd):
        print(f"window text: '{win32gui.GetWindowText(hwnd)}'")

win32gui.EnumWindows(callback, None)

It returns the this:

window text: ''
window text: ''
window text: 'PyCharm'
window text: 'Google Chrome'
window text: 'Einstellungen'
window text: ''
window text: 'Microsoft Store'
window text: 'Microsoft Store'
window text: 'Microsoft Text Input Application'
window text: ''
window text: ''
window text: ''
window text: ''
window text: ''
window text: 'Einstellungen'
window text: ''
window text: ''
window text: ''
window text: 'Program Manager'

I was looking into the GetWindowLong function but I was not able to find anything which would let me clearly differentiate a window.
I would be really thankful for any ideas.


Solution

  • When you enumerate the windows, you also get processes that do not have a window visible to the user. For example if you have a chrome window open, you'll get the handle for each child process as well.

    From MSDN on IsWindowVisible()

    If the specified window, its parent window, its parent's parent window, and so forth, have the WS_VISIBLE style, the return value is nonzero. Otherwise, the return value is zero.

    Reference: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-iswindowvisible

    Depending on your use case, you have some options:

    See: http://timgolden.me.uk/pywin32-docs/win32gui__GetClientRect_meth.html (win32GUI Documentation) https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect (MSDN)

    http://timgolden.me.uk/pywin32-docs/win32gui__GetWindowRect_meth.html (win32GUI Documentation) https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowrect (MSDN)

    See: http://timgolden.me.uk/pywin32-docs/win32gui__GetParent_meth.html (win32GUI Documentation) https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getparent (MSDN) https://learn.microsoft.com/en-us/windows/win32/winmsg/window-styles (MSDN)