Python,为什么返回的 win32api.ShellExecute 句柄不适用于 win32gui.GetWindowRect

标签 python winapi

好的,所以在下面的代码中

import win32api
import win32gui
hwnd = win32api.ShellExecute(None, "open", "notepad.exe", "test.txt", None, 6)
rect = win32gui.GetWindowRect(hwnd)

我成功打开记事本并收到返回值 >32 表示执行成功。在文档中:http://timgolden.me.uk/pywin32-docs/win32api__ShellExecute_meth.html 返回值被指定为实例句柄,因此我希望能够将此句柄用作 GetWindowRect 调用的参数。文档:http://timgolden.me.uk/pywin32-docs/win32gui__GetWindowRect_meth.html

在我的调试器中,我可以看到 hwnd 等于 {long}42,我的 GetWindowRect 调用返回错误 1400,窗口句柄无效。

那么为什么句柄不对,如何才能得到可用的句柄呢?

最佳答案

根据 Microsoft's documentation返回值是 HINSTANCE 类型,但它不是真正的实例,只能用于与各种错误代码进行比较。历史上,在 16 位窗口中,实例句柄用于标识特定的可执行文件或 DLL 实例,但即便如此,它也与窗口句柄不同。

Return value

Type: HINSTANCE

If the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications. It is not a true HINSTANCE, however. It can be cast only to an int and compared to either 32 or the following error codes below.

据我所知,获得可用窗口句柄的最佳方法是遍历系统中的顶层窗口,直到找到具有预期类和标题的窗口。

这是一段基于我多年前编写的代码摘录,用于查找具有匹配标题和类的窗口:

from win32gui import EnumWindows, GetClassName
from win32ui import CreateWindowFromHandle

def toplevelWindows(s, klass):
    res = []
    def callback(hwnd, arg):
        name = GetClassName(hwnd)
        w = CreateWindowFromHandle(hwnd)
        title = w.GetWindowText()
        if s in title or name==klass:
            res.append(w)
    EnumWindows(callback, 0)
    return res

关于Python,为什么返回的 win32api.ShellExecute 句柄不适用于 win32gui.GetWindowRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22487435/

相关文章:

python - GmailAPI : "Error sending test message to Cloud PubSub projects/[project-id]/topics/[topic-id] : User not authorized to perform this action."?

winapi - 无缓冲 CreateNamedPipe 用作 CreateProcess 的标准输出

c++ - 如何在同一线程中从 Windows 中的多个管道读取

c++ - 是否可以在 Windows 登录屏幕上显示我的窗口?

.net - WM_SETREDRAW 并丢失 z 顺序/焦点

python - 用python更新elasticsearch查询

python - 使用 Numpy 生成并填充二维数组

python - "sys-package-mgr*: can' t 创建包缓存目录“当使用 Jython 运行 python 脚本时

Python rpi GPIO输出控制基于GPIO输入和一天中的时间

c# - 捕获从另一个应用程序输入的文本