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

How to pass POINT structure to ElementFromPoint method in Python?

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

上重现了这个问题
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 中是这样定义的。