gpt4 book ai didi

python - 如何使用 pywin32 在 Python 中获取特定应用程序窗口的句柄?

转载 作者:行者123 更新时间:2023-12-02 02:55:52 30 4
gpt4 key购买 nike

我正在尝试修改一些截取 Windows 10 中特定应用程序窗口屏幕截图的 Python 代码。我正在尝试使用 win32ui/win32gui 模块pywin32 包用于此目的。这是损坏的代码:

def getWindow():
name = "Windows PowerShell"
window = win32ui.FindWindow(None, name)
windowDC = win32gui.GetWindowDC(window)

最后一行导致错误。这是控制台输出的相关部分:

  File ".\fake_file_name.py", line 9, in getWindow
windowDC = win32gui.GetWindowDC(window)
TypeError: The object is not a PyHANDLE object

我不是很熟悉 Python 的类型系统或错误消息,但这个错误使它看起来像 GetWindowDC 期待一个类型为 PyHANDLE 的参数。 The documentation我可以找到 win32gui.FindWindow 使它看起来像 PyHANDLE 确实是输出类型。

另一方面,这些非常相似的代码行来自一个确实起作用的函数:

    hwin = win32gui.GetDesktopWindow()
hwindc = win32gui.GetWindowDC(hwin)

这是 doc page对于 win32gui.GetDesktopWindow。如果之前显示的错误消息没有特别提到 PyHANDLE,我会假设 FindWindowGetDesktopWindow 返回不同且不兼容的类型。

谁能帮我理解这条错误消息的含义以及它出现的原因?我也对获取名称为“Windows Powershell”的窗口的设备上下文的示例代码感兴趣,因为我的损坏代码试图这样做。

其他信息: Documentation page对于 win32gui.GetWindowDC

最佳答案

你可以使用EnumWindows(),这将搜索所有的窗口,阅读MSDN doc :

import win32gui

def getShell():
thelist = []
def findit(hwnd,ctx):
if win32gui.GetWindowText(hwnd) == "Windows PowerShell": # check the title
thelist.append(hwnd)

win32gui.EnumWindows(findit,None)
return thelist

b = getShell()
print(b) # b is the list of hwnd,contains those windows title is "Windows PowerShell"

关于python - 如何使用 pywin32 在 Python 中获取特定应用程序窗口的句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61151811/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com