Skip to main content
 首页 » 编程设计

python之如何将 POINT 结构传递给 Python 中的 ElementFromPoint 方法

2024年10月01日8dudu

我正在尝试使用方法 IUIAutomation::ElementFromPoint 在 Python 中使用 comtypes 包。有很多如何在 C++ 中使用它的示例,但在 Python 中却没有。这个简单的代码在 64 位 Windows 10(Python 2.7 32 位)上重现了这个问题:

import comtypes.client 
 
UIA_dll = comtypes.client.GetModule('UIAutomationCore.dll') 
UIA_dll.IUIAutomation().ElementFromPoint(10, 10) 

我收到以下错误:

TypeError: Expected a COM this pointer as first argument 

以这种方式创建 POINT 结构也无济于事:

from ctypes import Structure, c_long 
 
class POINT(Structure): 
    _pack_ = 4 
    _fields_ = [ 
        ('x', c_long), 
        ('y', c_long), 
    ] 
 
point = POINT(10, 10) 
UIA_dll.IUIAutomation().ElementFromPoint(point) # raises the same exception 

请您参考如下方法:

您可以直接重用现有的 POINT 结构定义,如下所示:

import comtypes 
from comtypes import * 
from comtypes.client import * 
 
comtypes.client.GetModule('UIAutomationCore.dll') 
from comtypes.gen.UIAutomationClient import * 
 
# get IUIAutomation interface 
uia = CreateObject(CUIAutomation._reg_clsid_, interface=IUIAutomation) 
 
# import tagPOINT from wintypes 
from ctypes.wintypes import tagPOINT 
point = tagPOINT(10, 10) 
element = uia.ElementFromPoint(point) 
 
rc = element.currentBoundingRectangle # of type ctypes.wintypes.RECT 
print("Element bounds left:", rc.left, "right:", rc.right, "top:", rc.top, "bottom:", rc.bottom) 

确定 ElementFromPoint 的预期类型是什么,您只需转到您的 python 安装目录(对我来说是 C:\Users\<user>\AppData\Local\Programs\Python\Python36\Lib\site-packages\comtypes\gen )并检查其中的文件。它应该包含由 comtypes 自动生成的文件,包括用于 UIAutomationCore.dll 的文件。有趣的文件名以 _944DE083_8FB8_45CF_BCB7_C477ACB2F897(COM 类型库的 GUID)开头。

该文件包含以下内容:

COMMETHOD([], HRESULT, 'ElementFromPoint', 
          ( ['in'], tagPOINT, 'pt' ), 

这告诉您它需要一个 tagPOINT类型。这种类型定义在文件的开头,如下所示:

from ctypes.wintypes import tagPOINT 

之所以命名为 tagPOINT,是因为它在原始 Windows header 中是这样定义的.