2017-06-29 80 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

謝謝,西蒙!這正是我需要的。 –