2017-06-29 81 views
2

我试图使用comtypes包使用方法在Python IUIAutomation::ElementFromPoint。有很多例子说明如何在C++中使用它,但不在Python中使用它。这个简单的代码重新在64位Windows 10中的问题(Python 2.7版32位):如何在Python中将POINT结构传递给ElementFromPoint方法?

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 

回答

1

您可以直接重用现有的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定义。

+0

谢谢,西蒙!这正是我需要的。 –