Python,为什么返回的win32api.shell执行处理win32的工作图形用户界面

2024-06-16 11:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,那么在下面的代码中

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,无效的窗口句柄。在

那么为什么这个手柄是错的,我怎样才能得到一个有用的手柄呢?在


Tags: importnonehttpdocs句柄mepywin32uk
1条回答
网友
1楼 · 发布于 2024-06-16 11:27:45

根据Microsoft's documentation的说法,返回值属于HINSTANCE类型,但它不是一个真正的实例,只能用于与各种错误代码进行比较。过去在16位windows中,一个实例句柄被用来标识一个特定的可执行文件或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

相关问题 更多 >