comtypesを使ってWindowsのウィンドウを操作する

PythonでUI Automationを扱う情報が乏しく、妄想で試すw
Google Chromeの新しいタブを表示している状態からウィンドウを
  1. アクティブ化
  2. 最大化
  3. 最小化
  4. 復元
  5. 600x400にリサイズ
  6. x=100, y=200へ移動
を2秒間隔で実行するコードを示す:
# coding=utf-8

window_name = '新しいタブ - Google Chrome'

from time import sleep
import comtypes
from comtypes import CoCreateInstance
import comtypes.client
from comtypes.gen.UIAutomationClient import *

def get(base_element, condition, scope=TreeScope_Subtree):
	elements = base_element.FindAll(scope, condition)
	return [ elements.GetElement(i) for i in range(elements.Length) ]

uia = CoCreateInstance(CUIAutomation._reg_clsid_, interface=IUIAutomation, clsctx=comtypes.CLSCTX_INPROC_SERVER|comtypes.CLSCTX_INPROC_HANDLER|comtypes.CLSCTX_LOCAL_SERVER|comtypes.CLSCTX_REMOTE_SERVER)
root_element = uia.GetRootElement()

condition = uia.CreatePropertyCondition(UIA_NamePropertyId, window_name)
window = get(root_element, condition, TreeScope_Children)[0]

window.SetFocus() # アクティブ化
sleep(2)

wpif = window.GetCurrentPattern(UIA_WindowPatternId).QueryInterface(IUIAutomationWindowPattern) # WindowPattern
wpif.SetWindowVisualState(1) # 最大化
sleep(2)
wpif.SetWindowVisualState(2) # 最小化
sleep(2)
wpif.SetWindowVisualState(0) # 復元
sleep(2)

tpif = window.GetCurrentPattern(UIA_TransformPatternId).QueryInterface(IUIAutomationTransformPattern) # TransformPattern
tpif.Resize(600,400) # リサイズ
sleep(2)
tpif.Move(100,200) # 移動
2020/05/25 18:30
タグ