2

J'essaie d'utiliser la méthode IUIAutomation::ElementFromPoint en Python en utilisant comtypes package. Il existe de nombreux exemples d'utilisation en C++, mais pas en Python. Ce code simple reproduit le problème sur Windows 64 bits 10 (Python 2.7 32 bits):Comment passer la structure POINT à la méthode ElementFromPoint en Python?

import comtypes.client 

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

Je reçois l'erreur suivante:

TypeError: Expected a COM this pointer as first argument 

Création de la structure POINT cette façon ne permet pas ainsi:

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 

Répondre

1

Vous pouvez réutiliser la définition existante de structure POINT directement, comme celui-ci:

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) 

Pour déterminer quel est le type attendu pour ElementFromPoint, vous pouvez simplement aller à votre répertoire d'installation python (pour moi c'était C:\Users\<user>\AppData\Local\Programs\Python\Python36\Lib\site-packages\comtypes\gen) et vérifier les fichiers là-bas. Il devrait contenir des fichiers générés automatiquement par comtypes, y compris celui pour UIAutomationCore.dll. Le nom de fichier intéressant commence par _944DE083_8FB8_45CF_BCB7_C477ACB2F897 (le GUID de la bibliothèque de type COM).

Le fichier contient ceci:

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

Cela vous dit qu'il attend un type tagPOINT. Et ce type est défini un début du fichier comme ceci:

from ctypes.wintypes import tagPOINT 

Il est nommé tagPOINT parce que c'est la façon dont il est défini dans l'original Windows header.

+0

Merci, Simon! C'est exactement ce dont j'ai besoin. –