LoginSignup
38
46

More than 5 years have passed since last update.

PythonでUI Automation

Posted at

PythonでWindowsのGUI操作を自動化するのにUI Automationを使ってみる。
UI Automationは.NET版とCOM版があるが、CPythonから使いたいので、COM版で。
とりあえず、呼び出し方を調べたのでメモ。

UI Automationって?

UI Automationのススメ
http://blogs.msdn.com/b/japan_platform_sdkwindows_sdk_support_team_blog/archive/2011/05/26/ui-automation.aspx

UI Automation
http://msdn.microsoft.com/en-us/library/ee684009.aspx

前準備

まず、pip で comtypesを入れて、

pip install comtypes

次に、UI Automationのラッパーを生成しておく。

import comtypes
from comtypes.client import GetModule
GetModule('UIAutomationCore.dll')

Lib\site-packages\comtypes\gen にラッパーモジュールが生成される。
あとは UI Automation の MSDNリファレンスと _944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py を見比べて使い方を調べる。
(環境によってファイル名は違う場合があるかも)

UI Automationオブジェクトの取得

comtypes.gen.UIAutomationClientをインポートし、UI Automationオブジェクトを取得してあれこれする。

from comtypes.gen.UIAutomationClient import *
uia = CoCreateInstance(CUIAutomation._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER)

re = uia.GetRootElement()  # デスクトップの最上位要素の取得
print re.CurrentName       # 'デスクトップ'

電卓の例

UI Automation 経由で電卓(calc.exe)にアクセスしてみる。
上からの続きで。

import subprocess
calc = subprocess.Popen('calc.exe')    # 電卓起動
# pid指定でデスクトップの子要素から電卓を特定
cond = uia.CreatePropertyCondition(UIA_ProcessIdPropertyId, calc.pid)
calc_win = re.FindFirst(TreeScope_Children, cond)
print calc_win.CurrentName    # '電卓'

とりあえず、今回はここまで。
GUI操作の自動化までたどり着いてないので、次回に続く、かも。

38
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
46