def BatchRename():
    foxitWindow = automation.WindowControl(searchDepth=1,
                                           ClassName='classFoxitReader')
    foxitWindow.ShowWindow(automation.ShowWindow.ShowMaximized)
    ret = foxitWindow.SetActive()
    print('SetActive', ret)
    automation.Logger.Log(foxitWindow.Name[:-len(' - Foxit Reader')] + '\n')
    automation.SendKeys('{Ctrl}0')
    for aid in ['59583', '60682', '60683']:
        editToolBar = automation.ToolBarControl(searchFromControl=foxitWindow,
                                                AutomationId=aid,
                                                Name='Caption Bar')
        if editToolBar.Exists(0, 0):
            editToolBar.Click(-40, 0.5)
            automation.SendKeys('{Alt}y')
    paneWindow = automation.WindowControl(searchFromControl=foxitWindow,
                                          AutomationId='65280')
    bookmarkPane = automation.PaneControl(searchFromControl=paneWindow,
                                          searchDepth=1,
                                          foundIndex=1)
    l, t, r, b = bookmarkPane.BoundingRectangle
    #bookmarkButton = automation.ButtonControl(searchFromControl= bookmarkPane, Name = '书签') # can't find, but automation -a can find it, why
    if bookmarkPane.Name == '书签':
        if r - l < 40:
            bookmarkButton = automation.ControlFromPoint(l + 10, t + 40)
            if bookmarkButton.Name == '书签':
                bookmarkButton.Click(simulateMove=False)
    else:
        bookmarkButton = automation.ControlFromPoint(l + 10, t + 40)
        if bookmarkButton.Name == '书签':
            bookmarkButton.Click(simulateMove=False)
    tree = automation.TreeControl(searchFromControl=foxitWindow,
                                  ClassName='SysTreeView32')
    childItems = tree.GetChildren()
    bookMarks = []
    depth = 1
    for treeItem in childItems:
        if treeItem.ControlType == automation.ControlType.TreeItemControl:
            RenameTreeItem(tree, treeItem, bookMarks, depth)
    fout = open('rename_pdf_bookmark.txt', 'wt', encoding='utf-8')
    depth = 1
    for bookMark in bookMarks:
        DumpBookMark(fout, bookMark, depth)
    fout.close()
    if Renamed:
        automation.Logger.Log('rename pdf: ' + foxitWindow.Name)
        automation.SendKeys('{Ctrl}s')
        while '*' in foxitWindow.Name:
            time.sleep(0.5)
Exemplo n.º 2
0
def CalcOnWindows10():
    char2Id = {
        '0': 'num0Button',
        '1': 'num1Button',
        '2': 'num2Button',
        '3': 'num3Button',
        '4': 'num4Button',
        '5': 'num5Button',
        '6': 'num6Button',
        '7': 'num7Button',
        '8': 'num8Button',
        '9': 'num9Button',
        '.': 'decimalSeparatorButton',
        '+': 'plusButton',
        '-': 'minusButton',
        '*': 'multiplyButton',
        '/': 'divideButton',
        '=': 'equalButton',
        '(': 'openParanthesisButton',
        ')': 'closeParanthesisButton',
    }
    calcWindow = automation.WindowControl(searchDepth=1,
                                          ClassName='ApplicationFrameWindow',
                                          Name='Calculator')
    if not calcWindow.Exists(0, 0):
        subprocess.Popen('calc')
    calcWindow.SetTopmost()
    calcWindow.ButtonControl(AutomationId='NavButton').Click()
    calcWindow.ListItemControl(Name='Scientific Calculator').Click()
    calcWindow.ButtonControl(AutomationId='clearButton').Click()
    char2Button = {}
    for key in char2Id:
        char2Button[key] = calcWindow.ButtonControl(AutomationId=char2Id[key])
    Calc(calcWindow, char2Button, '1234 * (4 + 5 + 6) - 78 / 90')
    Calc(calcWindow, char2Button, '2*3.14159*10')
def main():
    firefoxWindow = automation.WindowControl(searchDepth=1,
                                             ClassName='MozillaWindowClass')
    if not firefoxWindow.Exists(0):
        automation.Logger.WriteLine('please run Firefox first',
                                    automation.ConsoleColor.Yellow)
        return
    firefoxWindow.ShowWindow(automation.ShowWindow.Maximize)
    firefoxWindow.SetActive()
    time.sleep(1)
    tab = firefoxWindow.TabControl()
    newTabButton = tab.ButtonControl(searchDepth=1)
    newTabButton.Click()
    edit = firefoxWindow.EditControl()
    # edit.Click()
    edit.SendKeys(
        'http://global.bing.com/?rb=0&setmkt=en-us&setlang=en-us{Enter}')
    time.sleep(2)
    searchEdit = automation.FindControl(
        firefoxWindow, lambda c, d: (isinstance(c, automation.EditControl) or
                                     isinstance(c, automation.ComboBoxControl))
        and c.Name == 'Enter your search term')
    # searchEdit.Click()
    searchEdit.SendKeys(
        'Python-UIAutomation-for-Windows site:github.com{Enter}', 0.05)
    link = firefoxWindow.HyperlinkControl(
        SubName='yinkaisheng/Python-UIAutomation-for-Windows')
    automation.Win32API.PressKey(automation.Keys.VK_CONTROL)
    link.Click()  #press control to open the page in a new tab
    automation.Win32API.ReleaseKey(automation.Keys.VK_CONTROL)
    newTab = tab.TabItemControl(
        SubName='yinkaisheng/Python-UIAutomation-for-Windows')
    newTab.Click()
    starButton = firefoxWindow.ButtonControl(Name='Star this repository')
    if starButton.Exists(5):
        automation.GetConsoleWindow().SetActive()
        automation.Logger.WriteLine(
            'Star Python-UIAutomation-for-Windows after 2 seconds',
            automation.ConsoleColor.Yellow)
        time.sleep(2)
        firefoxWindow.SetActive()
        time.sleep(1)
        starButton.Click()
        time.sleep(2)
    else:
        unstarButton = firefoxWindow.ButtonControl(
            Name='Unstar this repository')
        if unstarButton.Exists(0, 0):
            automation.GetConsoleWindow().SetActive()
            automation.Logger.WriteLine('Thank you. You have starred.',
                                        automation.ConsoleColor.Yellow)
Exemplo n.º 4
0
def CalcOnXP():
    chars = '0123456789.+-*/=()'
    calcWindow = automation.WindowControl(searchDepth=1, ClassName='SciCalc')
    if not calcWindow.Exists(0, 0):
        subprocess.Popen('calc')
    calcWindow.SetTopmost()
    calcWindow.SendKeys('{Alt}vs', 0.5)
    clearBtn = calcWindow.ButtonControl(Name='CE')
    clearBtn.Click()
    char2Button = {}
    for key in chars:
        char2Button[key] = calcWindow.ButtonControl(Name=key)
    Calc(calcWindow, char2Button, '1234 * (4 + 5 + 6) - 78 / 90')
    Calc(calcWindow, char2Button, '2*3.14159*10')
def GetPersonDetail():
    detailWindow = automation.WindowControl(searchDepth=1,
                                            ClassName='TXGuiFoundation',
                                            SubName='的资料')
    detailPane = detailWindow.PaneControl(Name='资料')
    details = ''
    for control, depth, remainCount in automation.WalkTree(
            detailPane, lambda c: c.GetChildren()):
        if control.ControlType == automation.ControlType.TextControl:
            details += control.Name
        elif control.ControlType == automation.ControlType.EditControl:
            details += control.CurrentValue() + '\n'
    details += '\n' * 2
    detailWindow.Click(0.95, 0.02)
    return details
Exemplo n.º 6
0
def ui_automation_initialize() -> Tuple[
    WindowControl, ButtonControl, PaneControl, ButtonControl, ListControl]:
    fr_window = uiautomation.WindowControl(
        ClassName='FineReader12MainWindowClass')
    italic = uiautomation.ButtonControl(searchFromControl=fr_window,
                                        Name='Kursywa (Ctrl+I)')
    text_window = uiautomation.PaneControl(searchFromControl=fr_window,
                                           ClassName='$FineReaderEditorClass$')
    copy_button_control = uiautomation.ButtonControl(
        searchFromControl=fr_window, Name='Kopiuj (Ctrl+C)')
    page_list_control = uiautomation.ListControl(searchFromControl=fr_window,
                                                 ClassName='SysListView32',
                                                 AutomationId='3080')
    return (fr_window, italic, text_window, copy_button_control,
            page_list_control)
def main():
    subprocess.Popen('mmc.exe devmgmt.msc')
    time.sleep(1)
    mmcWindow = automation.WindowControl(searchDepth=1,
                                         ClassName='MMCMainFrame')
    tree = mmcWindow.TreeControl()
    for item, depth in automation.WalkControl(tree, includeTop=True):
        if isinstance(
                item, automation.TreeItemControl
        ):  #or item.ControlType == automation.ControlType.TreeItemControl
            item.Select()
            if automation.ExpandCollapseState.Collapsed == item.CurrentExpandCollapseState(
            ):
                item.Expand(0)
            automation.Logger.WriteLine(' ' * (depth - 1) * 4 + item.Name,
                                        automation.ConsoleColor.Green)
            time.sleep(0.1)
Exemplo n.º 8
0
def CalcOnWindows7And8():
    char2Id = {
        '0': '130',
        '1': '131',
        '2': '132',
        '3': '133',
        '4': '134',
        '5': '135',
        '6': '136',
        '7': '137',
        '8': '138',
        '9': '139',
        '.': '84',
        '+': '93',
        '-': '94',
        '*': '92',
        '/': '91',
        '=': '121',
        '(': '128',
        ')': '129',
    }
    calcWindow = automation.WindowControl(searchDepth=1, ClassName='CalcFrame')
    if not calcWindow.Exists(0, 0):
        subprocess.Popen('calc')
    calcWindow.SetTopmost()
    calcWindow.SendKeys('{Alt}2')
    clearBtn = calcWindow.ButtonControl(
        foundIndex=8,
        Depth=3)  #test foundIndex and Depth, the 8th button is clear
    if clearBtn.AutomationId == '82':
        clearBtn.Click()
    char2Button = {}
    for key in char2Id:
        char2Button[key] = calcWindow.ButtonControl(AutomationId=char2Id[key])
    Calc(calcWindow, char2Button, '1234 * (4 + 5 + 6) - 78 / 90')
    Calc(calcWindow, char2Button, '2*3.14159*10')
def DemoCN():
    """for Chinese language"""
    thisWindow = automation.GetConsoleWindow()
    automation.Logger.ColorfulWrite(
        '我将运行<Color=Cyan>cmd</Color>并设置它的<Color=Cyan>屏幕缓冲区</Color>使<Color=Cyan>cmd</Color>一行能容纳很多字符\n\n'
    )
    time.sleep(3)

    automation.SendKeys('{Win}r')
    while not isinstance(automation.GetFocusedControl(),
                         automation.EditControl):
        time.sleep(1)
    automation.SendKeys('cmd{Enter}')
    cmdWindow = automation.WindowControl(SubName='cmd.exe')
    cmdWindow.TitleBarControl().RightClick()
    automation.SendKey(automation.Keys.VK_P)
    optionWindow = cmdWindow.WindowControl(SubName='属性')
    optionWindow.TabItemControl(SubName='选项').Click()
    optionTab = optionWindow.PaneControl(SubName='选项')
    checkBox = optionTab.CheckBoxControl(AutomationId='103')
    while checkBox.CurrentToggleState() != automation.ToggleState.On:
        checkBox.Click()
    checkBox = optionTab.CheckBoxControl(AutomationId='104')
    while checkBox.CurrentToggleState() != automation.ToggleState.On:
        checkBox.Click()
    optionWindow.TabItemControl(SubName='布局').Click()
    layoutTab = optionWindow.PaneControl(SubName='布局')
    layoutTab.EditControl(AutomationId='301').SetValue('300')
    layoutTab.EditControl(AutomationId='303').SetValue('3000')
    layoutTab.EditControl(AutomationId='305').SetValue('140')
    layoutTab.EditControl(AutomationId='307').SetValue('30')
    optionWindow.ButtonControl(AutomationId='1').Click()
    cmdWindow.SetActive()
    l, t, r, b = cmdWindow.BoundingRectangle
    automation.DragDrop(l + 50, t + 10, 50, 10)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '我将运行<Color=Cyan>记事本</Color>并输入<Color=Cyan>Hello!!!</Color>\n\n')
    time.sleep(3)

    subprocess.Popen('notepad')
    notepadWindow = automation.WindowControl(searchDepth=1,
                                             ClassName='Notepad')
    cx, cy = automation.Win32API.GetScreenSize()
    notepadWindow.MoveWindow(cx // 2, 0, cx // 2, cy // 2)
    time.sleep(0.5)
    notepadWindow.EditControl().SendKeys('Hello!!!', 0.05)
    time.sleep(1)

    dir = os.path.dirname(__file__)
    scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py'))

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '运行"<Color=Cyan>automation.py -h</Color>"显示帮助\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '运行"<Color=Cyan>automation.py -r -d1</Color>"显示所有顶层窗口, 即桌面的子窗口\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '运行"<Color=Cyan>automation.py -c</Color>"显示鼠标光标下的控件\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.MoveCursorToMyCenter()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '运行"<Color=Cyan>automation.py -a</Color>"显示鼠标光标下的控件和它的所有父控件\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.MoveCursorToMyCenter()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        '运行"<Color=Cyan>automation.py</Color>"显示当前激活窗口和它的所有子控件\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.EditControl().Click()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.WriteLine('演示结束,按Enter退出', automation.ConsoleColor.Green)
    input()
def DemoEN():
    """for other language"""
    thisWindow = automation.GetConsoleWindow()
    automation.Logger.ColorfulWrite('I will run <Color=Cyan>cmd</Color>\n\n')
    time.sleep(3)

    automation.SendKeys('{Win}r')
    while not isinstance(automation.GetFocusedControl(),
                         automation.EditControl):
        time.sleep(1)
    automation.SendKeys('cmd{Enter}')
    cmdWindow = automation.WindowControl(SubName='cmd.exe')
    l, t, r, b = cmdWindow.BoundingRectangle
    automation.DragDrop(l + 50, t + 10, 50, 10)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'I will run <Color=Cyan>Notepad</Color> and type <Color=Cyan>Hello!!!</Color>\n\n'
    )
    time.sleep(3)

    subprocess.Popen('notepad')
    notepadWindow = automation.WindowControl(searchDepth=1,
                                             ClassName='Notepad')
    cx, cy = automation.Win32API.GetScreenSize()
    notepadWindow.MoveWindow(cx // 2, 0, cx // 2, cy // 2)
    time.sleep(0.5)
    notepadWindow.EditControl().SendKeys('Hello!!!', 0.05)
    time.sleep(1)

    dir = os.path.dirname(__file__)
    scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py'))

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'run "<Color=Cyan>automation.py -h</Color>" to display the help\n\n')
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'run "<Color=Cyan>automation.py -r -d1</Color>" to display the top level windows, desktop\'s children\n\n'
    )
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'run "<Color=Cyan>automation.py -c</Color>" to display the control under mouse cursor\n\n'
    )
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.MoveCursorToMyCenter()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'run "<Color=Cyan>automation.py -a</Color>" to display the control under mouse cursor and its ancestors\n\n'
    )
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.MoveCursorToMyCenter()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)

    thisWindow.SetActive()
    automation.Logger.ColorfulWrite(
        'run "<Color=Cyan>automation.py</Color>" to display the active window\n\n'
    )
    time.sleep(3)

    cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05)
    notepadWindow.SetActive()
    notepadWindow.EditControl().Click()
    time.sleep(3)
    cmdWindow.SetActive(waitTime=2)
    time.sleep(3)

    thisWindow.SetActive()
    automation.Logger.WriteLine('press Enter to exit',
                                automation.ConsoleColor.Green)
    input()
Exemplo n.º 11
0
#!python3
# -*- coding:utf-8 -*-
import os
import sys
import subprocess

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(
    __file__))))  # not required after 'pip install uiautomation'
from uiautomation import uiautomation as automation

if __name__ == '__main__':
    isTop = 1
    print(sys.argv)

    if len(sys.argv) == 2:
        isTop = int(sys.argv[1])

    note = automation.WindowControl(searchDepth=1, ClassName='Notepad')
    if note.Exists(0, 0):
        note.SetTopmost(isTop)
    else:
        subprocess.Popen('notepad')
        note.Refind()
        note.SetTopmost(isTop)
        note.Move(0, 0)
        note.Resize(400, 300)
        edit = automation.EditControl(searchFromControl=note)
        edit.Click()
        automation.SendKeys('I\'m a topmost window!!!')
Exemplo n.º 12
0
def Analyze(sampleRate=90000,
            beginNo=0,
            maxPackets=0xFFFFFFFF,
            calculateLost=False):
    wireSharkWindow = automation.WindowControl(searchDepth=1,
                                               ClassName='Qt5QWindowIcon')
    if wireSharkWindow.Exists(0, 0):
        wireSharkWindow.SetActive()
    else:
        automation.Logger.WriteLine('can not find wireshark',
                                    automation.ConsoleColor.Yellow)
        return
    tree = wireSharkWindow.TreeControl(searchDepth=4, SubName='Packet list')
    left, top, right, bottom = tree.BoundingRectangle
    tree.Click(10, 30)
    automation.SendKeys('{Home}{Ctrl}{Alt}4')
    time.sleep(0.5)
    tree.Click(10, 30)
    headers = []
    headerFunctionDict = {
        'No': int,
        'Time': float,
        'Source': str,
        'Destination': str,
        'Protocol': str,
        'Length': int,
        'Info': str,
    }
    index = 0
    packets = []
    for item, depth in automation.WalkTree(
            tree,
            getFirstChildFunc=lambda c: c.GetFirstChildControl(),
            getNextSiblingFunc=lambda c: c.GetNextSiblingControl()):
        if isinstance(item, automation.HeaderControl):
            headers.append(item.Name.rstrip('.'))
        elif isinstance(item, automation.TreeItemControl):
            if index == 0:
                if len(packets) >= maxPackets:
                    break
                packet = PacketInfo()
            name = item.Name
            packet.__dict__[headers[index]] = headerFunctionDict[
                headers[index]](name)
            if headers[index] == 'Info':
                startIndex = name.find('Seq=')
                if startIndex > 0:
                    endIndex = name.find(' ', startIndex)
                    packet.Seq = int(name[startIndex + 4:endIndex].rstrip(','))
                startIndex = name.find('Time=')
                if startIndex > 0:
                    endIndex = name.find(' ', startIndex)
                    packet.TimeStamp = int(name[startIndex +
                                                5:endIndex].rstrip(','))
                    if packet.No >= beginNo:
                        packets.append(packet)
                        automation.Logger.WriteLine(
                            'No: {0[No]:<10}, Time: {0[Time]:<10}, Protocol: {0[Protocol]:<6}, Length: {0[Length]:<6}, Info: {0[Info]:<10},'
                            .format(packet.__dict__))
            index = (index + 1) % len(headers)
            if item.BoundingRectangle[3] >= bottom:
                automation.SendKeys('{PageDown}')
                time.sleep(0.1)

    automation.Logger.WriteLine('\n----------\nAnalyze Result:')
    seq = packets[0].Seq - 1
    lostSeqs = []
    framePackets = []
    lastTimeStamp = -1
    for p in packets:
        seq += 1
        if seq != p.Seq:
            lostSeqs.extend(range(seq, p.Seq))
            seq = p.Seq
        if lastTimeStamp < 0:
            framePackets.append(p)
        else:
            if lastTimeStamp == p.TimeStamp:
                framePackets[-1] = p
            else:
                framePackets.append(p)
        lastTimeStamp = p.TimeStamp

    lastTimeStamp = -1
    lastTime = -1
    totalDiff = 0
    frameCount = 0
    for p in framePackets:
        if lastTimeStamp < 0:
            automation.Logger.WriteLine(
                'No: {0[No]:<8}, Time: {0[Time]:<10}, Protocol: {0[Protocol]}, Length: {0[Length]:<6}, TimeStamp: {0[TimeStamp]:<15}'
                .format(p.__dict__))
        else:
            diffTimeStamp = p.TimeStamp - lastTimeStamp
            frameCount += 1
            totalDiff += diffTimeStamp
            sumTime = p.Time - framePackets[0].Time
            sumTimeFromTimeStamp = (p.TimeStamp -
                                    framePackets[0].TimeStamp) / sampleRate
            automation.Logger.WriteLine(
                'No: {0[No]:<8}, Time: {0[Time]:<10}, Protocol: {0[Protocol]}, Length: {0[Length]:<6}, TimeStamp: {0[TimeStamp]:<15}, 帧时间戳差值: {1:<6}, 帧实际时间差值: {2:<10.6f}, 实际接收时间: {3:<10.6f}, 时间戳时间: {4:<10.6f}, 提前时间:{5:<10.6f}'
                .format(p.__dict__, diffTimeStamp, p.Time - lastTime, sumTime,
                        sumTimeFromTimeStamp, sumTimeFromTimeStamp - sumTime))
        lastTime = p.Time
        lastTimeStamp = p.TimeStamp
    if frameCount:
        averageDiff = totalDiff // frameCount
        frameCount += 1
        seqCount = packets[-1].Seq - packets[0].Seq + 1
        totalTimeFromTimeStamp = (framePackets[-1].TimeStamp -
                                  framePackets[0].TimeStamp) / sampleRate
        realTime = framePackets[-1].Time - framePackets[0].Time
        if calculateLost:
            automation.Logger.WriteLine(
                '\n包总数: {0}, 帧数: {1}, 实际帧率:{2:.2f}, 平均时间戳: {3}, 总时间: {4:.6f}, 时间戳总时间: {5:.6f}, 丢包数: {6}({7:.2f}%), 丢包序号: {8}'
                .format(len(packets), frameCount, frameCount / realTime,
                        averageDiff, realTime, totalTimeFromTimeStamp,
                        len(lostSeqs),
                        len(lostSeqs) / seqCount, lostSeqs))
        else:
            automation.Logger.WriteLine(
                '\n包总数: {0}, 帧数: {1}, 实际帧率:{2:.2f}, 平均时间戳: {3}, 总时间: {4:.6f}, 时间戳总时间: {5:.6f}'
                .format(len(packets), frameCount, frameCount / realTime,
                        averageDiff, realTime, totalTimeFromTimeStamp))
Exemplo n.º 13
0
    var_ = GetParams("result")
    timeout_ = 30
    command_ = ""
    app = None

    result = False

    try:
        try:
            if len(str(TimoutMS).strip()) > 0:
                timeout_ = int(TimoutMS)
        except:
            pass
        command_ = getSelector(Selector)
        if len(str(command_)) > 1:
            windowScope = auto.WindowControl(**command_)

            result = windowScope.ExistsWindow(timeout_, 1)
            if result:
                windowScope.SetFocus()
                # windowScope.top_window().print_control_identifiers()
        else:
            raise Exception("No Selector")
        SetVar(var_, result)
    except Exception as e:
        print("\x1B[" + "31;40mAn error occurred\x1B[" + "0m")
        PrintException()
        SetVar(var_, False)

if module == "GetValue":
    Selector = GetParams("Selector")
Exemplo n.º 14
0
def testNotepadEN():
    consoleWindow = automation.GetConsoleWindow()
    consoleWindow.SetActive()
    automation.Logger.ColorfulWriteLine(
        '\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.'
    )
    time.sleep(2)
    automation.ShowDesktop()
    subprocess.Popen('notepad')
    #search notepad window, if searchFromControl is None, search from RootControl
    #searchDepth = 1 makes searching faster, only searches RootControl's children, not children's children
    window = automation.WindowControl(searchDepth=1,
                                      ClassName='Notepad',
                                      SubName='Untitled - Notepad')
    #if window.Exists(maxSearchSeconds = 3): #check before using it
    if automation.WaitForExist(window, 3):
        automation.Logger.WriteLine("Notepad exists now")
    else:
        automation.Logger.WriteLine("Notepad does not exist after 3 seconds",
                                    automation.ConsoleColor.Yellow)
    screenWidth, screenHeight = automation.Win32API.GetScreenSize()
    window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2,
                      screenHeight // 2)
    window.SetActive()
    edit = automation.EditControl(
        searchFromControl=window)  #or edit = window.EditControl()
    edit.Click(waitTime=0)
    edit.SetValue('hi你好')
    edit.SendKeys('{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2, 0)
    edit.SendKeys(text)
    edit.SendKeys('{Enter 3}0123456789{Enter}', waitTime=0)
    edit.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}', waitTime=0)
    edit.SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}', waitTime=0)
    edit.SendKeys('`~!@#$%^&*()-_=+{Enter}', waitTime=0)
    edit.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}{Ctrl}a')
    window.CaptureToImage('Notepad.png')
    edit.SendKeys('Image Notepad.png was captured, you will see it later.',
                  0.05)
    #find menu
    window.MenuItemControl(Name='Format').Click()
    window.MenuItemControl(Name='Font...').Click()
    windowFont = window.WindowControl(Name='Font')
    windowFont.ComboBoxControl(AutomationId='1140').Select('Western')
    windowFont.ButtonControl(Name='OK').Click()
    window.Close()
    if automation.WaitForDisappear(window, 3):
        automation.Logger.WriteLine("Notepad closed")
    else:
        automation.Logger.WriteLine("Notepad still exists after 3 seconds",
                                    automation.ConsoleColor.Yellow)
    # buttonNotSave = ButtonControl(searchFromControl = window, Name = 'Don\'t Save')
    # buttonNotSave.Click()
    # or send alt+n to not save and quit
    # automation.SendKeys('{Alt}n')
    # another way to find the button using lambda
    buttonNotSave = automation.FindControl(
        window, lambda control, depth: control.ControlType == automation.
        ControlType.ButtonControl and 'Don\'t Save' == control.Name)
    buttonNotSave.Click()
    subprocess.Popen('Notepad.png', shell=True)
    time.sleep(2)
    consoleWindow.SetActive()
    automation.Logger.WriteLine('script exits', automation.ConsoleColor.Cyan)
    time.sleep(2)
Exemplo n.º 15
0
def testNotepadCN():
    consoleWindow = automation.GetConsoleWindow()
    consoleWindow.SetActive()
    automation.Logger.ColorfulWriteLine(
        '\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.'
    )
    time.sleep(2)
    automation.ShowDesktop()
    #打开notepad
    subprocess.Popen('notepad')
    #查找notepad, 如果name有中文,python2中要使用Unicode
    window = automation.WindowControl(searchDepth=1,
                                      ClassName='Notepad',
                                      SubName='无标题 - 记事本')
    #可以判断window是否存在,如果不判断,找不到window的话会抛出异常
    #if window.Exists(maxSearchSeconds = 3):
    if automation.WaitForExist(window, 3):
        automation.Logger.WriteLine("Notepad exists now")
    else:
        automation.Logger.WriteLine("Notepad does not exist after 3 seconds",
                                    automation.ConsoleColor.Yellow)
    screenWidth, screenHeight = automation.Win32API.GetScreenSize()
    window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2,
                      screenHeight // 2)
    window.SetActive()
    #查找edit
    edit = automation.EditControl(
        searchFromControl=window)  #or edit = window.EditControl()
    edit.Click(waitTime=0)
    #python2中要使用Unicode, 模拟按键
    edit.SetValue('hi你好')
    edit.SendKeys('{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2, 0)
    edit.SendKeys(text)
    edit.SendKeys('{Enter 3}0123456789{Enter}', waitTime=0)
    edit.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{ENTER}', waitTime=0)
    edit.SendKeys('abcdefghijklmnopqrstuvwxyz{ENTER}', waitTime=0)
    edit.SendKeys('`~!@#$%^&*()-_=+{ENTER}', waitTime=0)
    edit.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{ENTER}', waitTime=0)
    edit.SendKeys(
        '™®①②③④⑤⑥⑦⑧⑨⑩§№☆★○●◎◇◆□℃‰€■△▲※→←↑↓〓¤°#&@\^_―♂♀{ENTER}{CTRL}a')
    window.CaptureToImage('Notepad.png')
    edit.SendKeys('Image Notepad.png was captured, you will see it later.',
                  0.05)
    #查找菜单
    window.MenuItemControl(Name='格式(O)').Click()
    window.MenuItemControl(Name='字体(F)...').Click()
    windowFont = window.WindowControl(Name='字体')
    windowFont.ComboBoxControl(AutomationId='1140').Select('中文 GB2312')
    windowFont.ButtonControl(Name='确定').Click()
    window.Close()
    if automation.WaitForDisappear(window, 3):
        automation.Logger.WriteLine("Notepad closed")
    else:
        automation.Logger.WriteLine("Notepad still exists after 3 seconds",
                                    automation.ConsoleColor.Yellow)

    # buttonNotSave = ButtonControl(searchFromControl = window, SubName = '不保存')
    # buttonNotSave.Click()
    # or send alt+n to not save and quit
    # automation.SendKeys('{Alt}n')
    # 使用另一种查找方法
    buttonNotSave = automation.FindControl(
        window, lambda control, depth: control.ControlType == automation.
        ControlType.ButtonControl and '不保存' in control.Name)
    buttonNotSave.Click()
    subprocess.Popen('Notepad.png', shell=True)
    time.sleep(2)
    consoleWindow.SetActive()
    automation.Logger.WriteLine('script exits', automation.ConsoleColor.Cyan)
    time.sleep(2)