18
08

UIAutomation API

SetTopmost(True):将窗体设置为顶层;MoveToCenter():将窗体居中显示;MetroClose():关闭win8以后出现的新菜单MetroUI;SetActive():设置一个程序被执行得间隔时间。


1.uiautomation方法


(1)WindowContrl(searchDepth,ClassName,SubName)


查找窗口中的程序;可用window.Exists(maxSearchSeconds)来判断此窗口是否存在;

源代码如下:


class WindowControl(Control, TransformPattern, WindowPattern, DockPattern):
    def __init__(self, element = 0, searchFromControl = None, searchDepth = 0xFFFFFFFF,   

searchWaitTime = SEARCH_INTERVAL, foundIndex = 1, **searchPorpertyDict):
        Control.__init__(self, element, searchFromControl, searchDepth, searchWaitTime,

foundIndex, **searchPorpertyDict)
        self.AddSearchProperty(ControlType = ControlType.WindowControl)

    def SetTopmost(self, isTopmost = True):
        return Win32API.SetWindowTopmost(self.Handle, isTopmost)

    def MoveToCenter(self):
        left, top, right, bottom = self.BoundingRectangle
        width, height = right - left, bottom - top
        screenWidth, screenHeight = Win32API.GetScreenSize()
        x, y = (screenWidth-width)//2, (screenHeight-height)//2
        if x < 0: x = 0
        if y < 0: y = 0
        return Win32API.SetWindowPos(self.Handle, SWP.HWND_TOP, x, y, 0, 0,  

SWP.SWP_NOSIZE)

    def MetroClose(self, waitTime = OPERATION_WAIT_TIME):
        """only works in Windows 8/8.1, if current window is Metro UI"""
        window = WindowControl(searchDepth = 1, ClassName =

METRO_WINDOW_CLASS_NAME)
        if window.Exists(0, 0):
            screenWidth, screenHeight = Win32API.GetScreenSize()
            Win32API.MouseMoveTo(screenWidth//2, 0, waitTime = 0)
            Win32API.MouseDragDrop(screenWidth//2, 0, screenWidth//2, screenHeight,

waitTime = waitTime)
        else:
            Logger.WriteLine('Window is not Metro!', ConsoleColor.Yellow)

    def SetActive(self, waitTime = OPERATION_WAIT_TIME):
        curState = self.CurrentWindowVisualState()
        if curState == WindowVisualState.Minimized:
            self.ShowWindow(ShowWindow.Restore)
        elif curState == WindowVisualState.Maximized:
            self.ShowWindow(ShowWindow.Maximize)
        else:
            self.ShowWindow(ShowWindow.Show)
        ret = Win32API.SetForegroundWindow(self.Handle)  #maybe fail if foreground

windows's process is not python
        time.sleep(waitTime)
        return ret


从上面的源码中可以看出,WindowContrl类下面有四个方法:

SetTopmost(True):将窗体设置为顶层;MoveToCenter():将窗体居中显示;MetroClose():关闭win8以后出现的新菜单MetroUI;SetActive():设置一个程序被执行得间隔时间。方法可以这样在python中使用,代码如下:


以计算器为例

calcwindow = uiautomation.WindowControl(searchDepth=1, Name='计算器')

#窗体居中显示
calcwindow.MoveToCenter()

#窗体置顶
calcwindow.SetTopmost(True)

#控制操作间隔
calcwindow.SetActive(20)

#只针对win8,关闭MetroUI
calcwindow.MetroClose(10)

 

(2)EditControl(searchFromControl)


查找编辑位置,找到后可用DoubleClick()来改变电脑的focus;edit.SetValue("string")输入值,源码如下:


class EditControl(Control, RangeValuePattern, TextPattern, ValuePattern):
    def __init__(self, element = 0, searchFromControl = None, searchDepth = 0xFFFFFFFF,

searchWaitTime = SEARCH_INTERVAL, foundIndex = 1, **searchPorpertyDict):
        Control.__init__(self, element, searchFromControl, searchDepth, searchWaitTime,

foundIndex, **searchPorpertyDict)
        self.AddSearchProperty(ControlType = ControlType.EditControl)


此类继承其父类的所有非私有方法。常用方法使用代码如下:


edit = uiautomation.EditControl(searchFromControl = musicwindow, foundIndex =

1,ProcessId='xxxx')

#点击元素,将光标放入元素中

edit.Click()

#先文本框输入文字

edit.SendKeys(‘你好!’)

 

(3)Win32API.SendKeys("string")


如果已在编辑位置,则可用此方法来输入值,{Ctrl}为ctrl键,其他类似;{@  8}格式可输入8个@,对于数字也可实现此功能,但对于字母不能,源码代码量较大,这里就不展示了,大家可以在python中自行查看,此类的功能非常多,涉及鼠标、键盘以及窗体的操作。常用输入信息代码如下:


#已经有光标在输入框内的时候,也可以直接使用

uiautomation.Win32API.SendKeys(‘你好!’)

 

(4) MenuItemControl(searchFromControl,Name)

查找菜单按钮,源码如下


class MenuBarControl(Control):
    def __init__(self, element = 0, searchFromControl = None, searchDepth = 0xFFFFFFFF,

searchWaitTime = SEARCH_INTERVAL, foundIndex = 1, **searchPorpertyDict):
        Control.__init__(self, element, searchFromControl, searchDepth, searchWaitTime,

foundIndex, **searchPorpertyDict)
        self.AddSearchProperty(ControlType = ControlType.MenuBarControl)


使用代码如下:


mubar = uiautomation.MenuBarControl(searchFromControl = musicwindow, foundIndex =

1,ProcessId='xxxx')

mubar.Click()

 

(5)ComboBoxControl(searchFromControl,AutomationId) 

      

查找下拉框,然后在此基础上用Select("name")方法来选择需要的选项;

 

(6)BottonControl(searchFromControl,Name,SubName)


查找按钮;

calcwindow = uiautomation.WindowControl(searchDepth=1, Name='计算器')

calcwindow.ButtonControl(Name='7').Click()


(7) automation.FindControl(firefoxWindow,lambda c:(isinstance(c, automation.EditControl)

or isinstance(c, automation.ComboBoxControl)) and c.Name == 'Enter your search term')

按条件搜索handle


baiduedit = automation.FindControl(huohu,lambda c,d:isinstance(c,automation.EditControl),

foundIndex=3)
baiduedit.SendKeys(u"在线工具库",0.5)

 

2.对找到句柄常用操作


(1) Click() 点击;

(2) RighClik() 右键点击;

(3) SendKeys() 发送字符;

(4) SetValue()传值,一般对EditControl用;

 

3.对windows程序常用操作


(1)subprocess.Popen('Name')   用进程打开程序;

(2)window.Close()        关闭窗口;

(3)window.SetActive()        使用;

(4)window.SetTopMost()     设置为顶层

(5)window.ShowWindow(uiautomation.ShowWindow.Maximize)  窗口最大化

(6)window.CaptureToImage('Notepad.png')  截图;

(7)uiautomation.Win32API.PressKey(uiautomation.Keys.VK_CONTROL)    按住Ctrl键

(8)uiautomation.Win32API.ReleaseKey(uiautomation.Keys.VK_CONTROL) 释放Ctrl键

(9)automation.GetConsoleWindow()      #return console window that runs python,打开控制台

(10)automation.Logger.ColorfulWriteLine('\nI will open <Color=Green>Notepad</Color> and

<Color=Yellow>automate</Color> it. Please wait for a while.')  控制台传值(彩色字体),普通传值用WriteLine;

(11)automation.ShowDesktop() 显示桌面;


下期推送:UIAutomation使用中的问题



为了答谢大家对蜗牛学院的支持,蜗牛学院将会定期对大家免费发放干货,敬请关注蜗牛学院的官方微信。


20190320_095757_834.jpg






版权所有,转载本站文章请注明出处:蜗牛学苑, https://www.woniuxy.cn/article/258