python - 使用 win32gui 列出所有窗口

标签 python windows winapi win32gui

我正在尝试使用 Python 和 win32gui 模块列出 Microsoft Windows 10 的所有窗口。问题是,根据我的理解,还列出了一些没有窗口的进程。

当我在仅打开 Chrome 和 PyCharm 的情况下运行此代码时

import win32gui

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

win32gui.EnumWindows(callback, None)

它返回这个:

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'

我正在研究 GetWindowLong 函数,但找不到任何可以让我清楚地区分窗口的内容。
如果有任何想法,我将非常感激。

最佳答案

当您枚举窗口时,您还会获得没有用户可见窗口的进程。例如,如果您打开了一个 Chrome 窗口,您还将获得每个子进程的句柄。

来自 MSDN 上的 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.

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

根据您的用例,您有一些选择:

  • 您可以使用 GetClientRect()(用于工作空间)或 GetWindowRect()(用于总窗口空间,包括阴影等窗口效果)并检查窗口是否实际占用屏幕上的空间。

参见: http://timgolden.me.uk/pywin32-docs/win32gui__GetClientRect_meth.html (win32GUI 文档) 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 文档) https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowrect (MSDN)

  • 您可以检查窗口样式中的 WS_CHILD 标志,或使用 GetParent() 来查看窗口是否是子窗口,如果是,则将其排除。您可能需要包装

参见: http://timgolden.me.uk/pywin32-docs/win32gui__GetParent_meth.html (win32GUI 文档) 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)

  • 您可以简单地检查窗口的标题是否至少包含一个字符,这将允许您获得可见的子窗口的 HWND。

关于python - 使用 win32gui 列出所有窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69712306/

相关文章:

python - Tensorflow 的计算时间在非常简单的 "for loop"中逐渐变慢

windows - vmrun.exe 的多个问题

windows - 错误 1053 : the service did not respond to the start or control request in a timely fashion

c++ -::GetPrivateProfileString 读取 INI 文件的整个部分

c++ - 根据镜像效果、亮度和缩放级别读取 jpeg 文件

python - 为Python打开的一般文件,不关心文件压缩

Python tic tac toe 检测作弊

python - wxpython 的 DRAG 鼠标光标 ID 是什么?

c++ - 推荐的开源分析器

C++ 如何设置菜单项的颜色?