我尝试使用 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
答案 0 :(得分:2)
您可以直接重用现有的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类型的lib&#39; GUID)开头。
该文件包含:
COMMETHOD([], HRESULT, 'ElementFromPoint',
( ['in'], tagPOINT, 'pt' ),
这告诉您它需要tagPOINT
类型。这种类型被定义为文件的开头,如下所示:
from ctypes.wintypes import tagPOINT
它命名为tagPOINT,因为它是如何在原始Windows header中定义的。