Example #1
0
def BatchRename():
    foxitWindow = automation.WindowControl(searchDepth=1,
                                           ClassName='classFoxitReader')
    foxitWindow.ShowWindow(automation.ShowWindow.ShowMaximized)
    foxitWindow.SetActive()
    automation.Logger.Log(foxitWindow.Name[:-len(' - Foxit Reader')] + '\n')
    time.sleep(1)
    automation.SendKeys('{Ctrl}0')
    time.sleep(0.5)
    editToolBar = automation.ToolBarControl(searchFromControl=foxitWindow,
                                            AutomationId='59583',
                                            Name='Caption Bar')
    if editToolBar.Exists(0, 0):
        editToolBar.Click(0.96, 0.5)
        time.sleep(0.5)
        automation.SendKeys('{Alt}y')
        time.sleep(0.5)
    editToolBar = automation.ToolBarControl(searchFromControl=foxitWindow,
                                            AutomationId='60683',
                                            Name='Caption Bar')
    if editToolBar.Exists(0, 0):
        editToolBar.Click(0.96, 0.5)
        time.sleep(0.5)
        automation.SendKeys('{Alt}y')
        time.sleep(0.5)
    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')
        time.sleep(0.5)
        while '*' in foxitWindow.Name:
            time.sleep(0.5)
def testNotepadCN():
    automation.ShowDesktop()
    #打开notepad
    subprocess.Popen('notepad')
    #查找notepad, 如果name有中文,python2中要使用Unicode
    window = automation.WindowControl(searchDepth=1,
                                      ClassName='Notepad',
                                      SubName=u'无标题 - 记事本')
    #可以判断window是否存在,如果不判断,找不到window的话会抛出异常
    #if window.Exists(maxSearchSeconds = 3):
    screenWidth, screenHeight = automation.Win32API.GetScreenSize()
    window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2,
                      screenHeight // 2)
    #查找edit
    edit = automation.EditControl(searchFromControl=window)
    edit.DoubleClick()
    time.sleep(1)
    #python2中要使用Unicode, 模拟按键
    edit.SetValue(u'hi你好')
    automation.SendKeys(u'{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2)
    automation.SendKeys(text)
    automation.SendKeys('{Enter 3}0123456789{Enter}')
    automation.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}')
    automation.SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}')
    automation.SendKeys('`~!@#$%^&*()-_=+{ENTER}')
    automation.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}{Ctrl}a')
    time.sleep(1)
    window.CaptureToImage('Notepad.png')
    automation.SendKeys(
        'Image Notepad.png was captured, you will see it later.', 0.05)
    time.sleep(1)
    #查找菜单
    menuItemFormat = automation.MenuItemControl(searchFromControl=window,
                                                Name=u'格式(O)')
    menuItemFont = automation.MenuItemControl(searchFromControl=window,
                                              Name=u'字体(F)...')
    windowFont = automation.WindowControl(searchFromControl=window, Name=u'字体')
    comboScript = automation.ComboBoxControl(searchFromControl=windowFont,
                                             AutomationId='1140')
    buttonOK = automation.ButtonControl(searchFromControl=windowFont,
                                        Name=u'确定')
    menuItemFormat.Click()
    menuItemFont.Click()  #or automation.SendKey(automation.Keys.VK_F)
    comboScript.Select(u'中文 GB2312')
    buttonOK.Click()
    time.sleep(1)
    window.Close()
    time.sleep(1)

    # buttonNotSave = ButtonControl(searchFromControl = window, SubName = u'不保存')
    # buttonNotSave.Click()
    # or send alt+n to not save and quit
    # automation.SendKeys('{Alt}n')
    # 使用另一种查找方法
    buttonNotSave = automation.FindControl(
        window, lambda control: control.ControlType == automation.ControlType.
        ButtonControl and u'不保存' in control.Name)
    buttonNotSave.Click()
    os.popen('Notepad.png')
Example #3
0
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 = automation.TabControl(searchFromControl=firefoxWindow)
    newTabButton = automation.ButtonControl(searchFromControl=tab,
                                            searchDepth=1)
    newTabButton.Click()
    edit = automation.EditControl(searchFromControl=firefoxWindow)
    edit.Click()
    automation.SendKeys(
        'http://global.bing.com/?rb=0&setmkt=en-us&setlang=en-us{Enter}')
    time.sleep(2)
    searchEdit = automation.FindControl(
        firefoxWindow, lambda c: (isinstance(c, automation.EditControl) or
                                  isinstance(c, automation.ComboBoxControl))
        and c.Name == 'Enter your search term')
    searchEdit.Click()
    automation.SendKeys(
        'Python-UIAutomation-for-Windows site:github.com{Enter}', 0.05)
    link = automation.HyperlinkControl(
        searchFromControl=firefoxWindow,
        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 = automation.TabItemControl(
        searchFromControl=tab,
        SubName='yinkaisheng/Python-UIAutomation-for-Windows')
    newTab.Click()
    starButton = automation.ButtonControl(searchFromControl=firefoxWindow,
                                          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)
def testNotepadEN():
    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
    #pass
    screenWidth, screenHeight = automation.Win32API.GetScreenSize()
    window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2,
                      screenHeight // 2)
    edit = automation.EditControl(searchFromControl=window)
    window.SetActive()
    time.sleep(1)
    edit.DoubleClick()
    #use unicode string
    edit.SetValue(u'hi你好')
    automation.SendKeys(u'{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2)
    automation.SendKeys(text)
    automation.SendKeys('{ENTER 3}0123456789{ENTER}')
    automation.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{ENTER}')
    automation.SendKeys('abcdefghijklmnopqrstuvwxyz{ENTER}')
    automation.SendKeys('`~!@#$%^&*()-_=+{ENTER}')
    automation.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{ENTER}{CTRL}a')
    time.sleep(1)
    window.CaptureToImage('Notepad.png')
    automation.SendKeys(
        'Image Notepad.png was captured, you will see it later.', 0.05)
    time.sleep(1)
    menuItemFormat = automation.MenuItemControl(searchFromControl=window,
                                                Name='Format')
    menuItemFont = automation.enuItemControl(searchFromControl=window,
                                             Name='Font...')
    windowFont = automation.WindowControl(searchFromControl=window,
                                          Name='Font')
    comboScript = automation.ComboBoxControl(searchFromControl=windowFont,
                                             AutomationId='1140')
    buttonOK = automation.ButtonControl(searchFromControl=windowFont,
                                        Name='OK')
    menuItemFormat.Click()
    menuItemFont.Click()  #or automation.SendKey(automation.Keys.VK_F)
    comboScript.Select('Western')
    buttonOK.Click()
    time.sleep(1)
    window.Close()
    time.sleep(1)
    # 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: control.ControlType == automation.ControlType.
        ButtonControl and 'Don\'t Save' == control.Name)
    buttonNotSave.Click()
    os.popen('Notepad.png')
Example #5
0
def RenameTreeItem(tree, treeItem, bookMarks, depth, removeChapter=True):
    treeItem.ScrollIntoView()
    if depth > TreeDepth:
        return
    name = treeItem.Name
    if not name.strip():
        return
    newName = RenameFunction(name, removeChapter)
    if newName.startswith('Appendix'):
        removeChapter = False
    bookMark = BookMark(name, newName)
    bookMarks.append(bookMark)
    if newName != name:
        global Renamed
        Renamed = True
        time.sleep(0.1)
        treeItem.RightClick(simulateMove=False)
        # FoxitReader书签右键菜单(BCGPToolBar,非Windows菜单)弹出后,枚举不到菜单,但从屏幕点上ControlFromPoint能获取到菜单, todo
        # 采用特殊处理获取重命名菜单
        time.sleep(0.2)
        x, y = automation.Win32API.GetCursorPos()
        menuItem = automation.ControlFromPoint(x + 2, y + 2)
        if menuItem.ControlType == automation.ControlType.MenuItemControl:
            #鼠标右下方弹出菜单
            while not (menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename'):
                y += 20
                menuItem = automation.ControlFromPoint(x + 2, y)
                if menuItem.ControlType != automation.ControlType.MenuItemControl:
                    break
        else:
            #鼠标右上方弹出菜单
            menuItem = automation.ControlFromPoint(x + 2, y - 2)
            while not (menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename'):
                y -= 20
                menuItem = automation.ControlFromPoint(x + 2, y)
                if menuItem.ControlType != automation.ControlType.MenuItemControl:
                    break
        if menuItem.ControlType != automation.ControlType.MenuItemControl:
            automation.Logger.Log('this pdf not support editing')
            exit(0)
        menuItem.Click(simulateMove=False)
        edit = automation.EditControl(searchFromControl=tree, searchDepth=1)
        edit.SetValue(newName)
        automation.SendKeys('{Enter}')
        automation.Logger.Write('rename: ')
        automation.Logger.WriteLine(name, automation.ConsoleColor.Green)
        automation.Logger.Write('    to: ')
        automation.Logger.WriteLine(newName, automation.ConsoleColor.Green)
    if depth + 1 > TreeDepth:
        return
    treeItem.Expand()
    childItems = treeItem.GetChildren()
    if childItems:
        treeItem.Expand()
        for child in childItems:
            RenameTreeItem(tree, child, bookMark.children, depth + 1,
                           removeChapter)
Example #6
0
def main():
    print('请把鼠标放在QQ群聊天窗口中的一个成员上面,3秒后获取\n')
    time.sleep(3)
    listItem = automation.ControlFromCursor()
    if listItem.ControlType != automation.ControlType.ListItemControl:
        print('没有放在群成员上面,程序退出!')
        return
    consoleWindow = automation.GetConsoleWindow()
    consoleWindow.SetActive()
    qqWindow = listItem.GetTopWindow()
    list = listItem.GetParentControl()
    allListItems = list.GetChildren()
    for listItem in allListItems:
        automation.Logger.WriteLine(listItem.Name)
    answer = input('是否获取详细信息?按y和Enter继续\n')
    if answer.lower() == 'y':
        print('\n3秒后开始获取QQ群成员详细资料,您可以一直按住F10键暂停脚本')
        time.sleep(3)
        qqWindow.SetActive()
        time.sleep(0.5)
        #确保群里第一个成员可见在最上面
        left, top, right, bottom = list.BoundingRectangle
        while allListItems[0].BoundingRectangle[1] < top:
            automation.Win32API.MouseClick(right - 5, top + 20)
            time.sleep(0.5)
        for listItem in allListItems:
            if listItem.ControlType == automation.ControlType.ListItemControl:
                if automation.Win32API.IsKeyPressed(automation.Keys.VK_F10):
                    consoleWindow.SetActive()
                    input('\n您暂停了脚本,按Enter继续\n')
                    qqWindow.SetActive()
                    time.sleep(0.5)
                listItem.RightClick()
                menu = automation.MenuControl(searchDepth=1,
                                              ClassName='TXGuiFoundation')
                menuItems = menu.GetChildren()
                for menuItem in menuItems:
                    if menuItem.Name == '查看资料':
                        menuItem.Click()
                        break
                automation.Logger.WriteLine(listItem.Name,
                                            automation.ConsoleColor.Green)
                automation.Logger.WriteLine(GetPersonDetail())
                listItem.Click()
                time.sleep(0.5)
                automation.SendKeys('{Down}')
                time.sleep(0.5)
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 = automation.TreeControl(searchFromControl=wireSharkWindow,
                                  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))
#!python3
# -*- coding:utf-8 -*-
import sys
import subprocess
import 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)
        edit = automation.EditControl(searchFromControl= note)
        edit.Click()
        automation.SendKeys('I\'m a topmost window!!!')

Example #9
0
def main():

    # mainWindow=automation.WindowControl(searchDepth=1, ClassName='TXGuiFoundation',Name='');
    # mainWindow.ShowWindow(automation.ShowWindow.Maximize)
    # mainWindow.SetActive()
    # # 群聊按钮
    # groupBtn=automation.ButtonControl(searchFromControl=mainWindow);
    #
    #
    #
    # # groupBtn=automation.FindControl(searchFromControl=mainWindow);
    #
    # groupsControl=automation.ListItemControl(searchFromControl=mainWindow,Name='我的QQ群')
    # containControl=groupsControl.GetNextSiblingControl();
    # groupItems=automation.PaneControl.GetChildren(containControl);
    # for grop in groupItems:
    #     automation.ListItemControl.RightClick(grop)
    #     automation.SendKey("{Down}");
    #     print(grop)
    #     time.sleep(5)
    # return




    qqWindow = automation.WindowControl(searchDepth=1, ClassName='TXGuiFoundation')
    if not qqWindow.Exists(0):
        automation.Logger.WriteLine('please run QQ first', automation.ConsoleColor.Yellow)
        return
    qqWindow.ShowWindow(automation.ShowWindow.Maximize)
    qqWindow.SetActive()
    time.sleep(1)

    # 群聊窗口输入框
    # edit = automation.EditControl(searchFromControl=qqWindow, Name='输入')
    # if !edit
    #     print('没有找到对应的群输入框')
    #     return
    # edit.Click()
    # automation.SendKeys('有人在吗? {Enter}')
    # automation.SendKeys("{Ctrl}{Enter}")
    # time.sleep(2)

    listControl = automation.ListControl(searchFromControl=qqWindow, Name='')
    listItem = listControl.GetChildren()
    # 确保群里第一个成员可见在最上面
    left, top, right, bottom = listControl.BoundingRectangle
    while listItem[0].BoundingRectangle[1] < top:
        automation.Win32API.MouseClick(right - 5, top + 5)
    for item in listItem:
        if '管理员' in item.Name or '群主' in item.Name:
            item.Click()
            time.sleep(0.5)
            automation.SendKeys('{Down}')
            continue;
        item.RightClick()
        itemName = item.Name
        print(item)
        menu = automation.MenuControl(searchDepth=1, ClassName='TXGuiFoundation')
        menuItems = menu.GetChildren()
        for menuItem in menuItems:
            if menuItem.Name == '发送消息':
                menuItem.Click()
                time.sleep(0.5)
                currentTalkWin = automation.WindowControl(searchDepth=1, ClassName='TXGuiFoundation')
                currentTalkWin.SetActive()
                # time.sleep(0.5)
                edit = automation.EditControl(searchFromControl=currentTalkWin, Name='输入')
                edit.Click()
                text = '''
【皮尔卡丹】家纺纯棉四件套 法式情调家纺{Enter}
【天猫89元】【23花色入】【送运险费】{Enter}
优惠券:https://shop.m.taobao.com/shop/coupon.htm?sellerId=2369408650&activityId=a5304665cb824928a35d81b73cfaa20b{Enter}
抢购链接:http://yqt.so/Re49Td{Enter}
【法国大牌】{Enter}
                '''
                automation.SendKeys(text+' {Enter}')
                automation.SendKeys("{Alt}{F4}")
                break
        item.Click()
        time.sleep(0.5)
        automation.SendKeys('{Down}')
        time.sleep(0.5)
    return

    searchEdit = automation.FindControl(qqWindow,
                                        lambda c:
                                        (isinstance(c, automation.EditControl) or isinstance(c,
                                                                                             automation.ComboBoxControl)) and c.Name == 'Enter your search term'
                                        )
    searchEdit.Click()
    automation.SendKeys('Python-UIAutomation-for-Windows site:github.com{Enter}', 0.05)
    link = automation.HyperlinkControl(searchFromControl=qqWindow,
                                       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 = automation.TabItemControl(searchFromControl=tab, SubName='yinkaisheng/Python-UIAutomation-for-Windows')
    newTab.Click()
    starButton = automation.ButtonControl(searchFromControl=qqWindow, 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)
        qqWindow.SetActive()
        time.sleep(1)
        starButton.Click()
        time.sleep(2)
Example #10
0
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.Win32API.MouseDragTo(l + 50, t + 10, 50, 10)

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

    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.join(dir, 'automation.py')

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

    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(2)

    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(2)

    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(2)

    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(2)

    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.Cyan)
    input()
Example #11
0
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.Win32API.MouseDragTo(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.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()
Example #12
0
File: App.py Project: peisheng/test
def main():
    qqWindow = automation.WindowControl(searchDepth=1,
                                        ClassName='TXGuiFoundation',
                                        title='净网大师官方PC群1')
    if not qqWindow.Exists(0):
        automation.Logger.WriteLine('please run QQ first',
                                    automation.ConsoleColor.Yellow)
        return
    qqWindow.ShowWindow(automation.ShowWindow.Maximize)
    qqWindow.SetActive()
    time.sleep(1)

    # 群聊窗口输入框
    # edit = automation.EditControl(searchFromControl=qqWindow, Name='输入')
    # if !edit
    #     print('没有找到对应的群输入框')
    #     return
    # edit.Click()
    # automation.SendKeys('有人在吗? {Enter}')
    # automation.SendKeys("{Ctrl}{Enter}")
    # time.sleep(2)

    listControl = automation.ListControl(searchFromControl=qqWindow, Name='')
    listItem = listControl.GetChildren()
    # 确保群里第一个成员可见在最上面
    left, top, right, bottom = listControl.BoundingRectangle
    while listItem[0].BoundingRectangle[1] < top:
        automation.Win32API.MouseClick(right - 5, top + 5)
    for item in listItem:
        item.RightClick()
        itemName = item.Name
        print(item)
        menu = automation.MenuControl(searchDepth=1,
                                      ClassName='TXGuiFoundation')
        menuItems = menu.GetChildren()
        for menuItem in menuItems:
            if menuItem.Name == '发送消息':
                menuItem.Click()
                time.sleep(0.5)
                currentTalkWin = automation.WindowControl(
                    searchDepth=1, ClassName='TXGuiFoundation')
                # currentTalkWin.ShowWindow(automation.ShowWindow.Maximize)
                currentTalkWin.SetActive()
                time.sleep(0.5)
                edit = automation.EditControl(searchFromControl=currentTalkWin,
                                              Name='输入')
                edit.Click()
                automation.SendKeys('有人在吗? {Enter}')
                automation.SendKeys("{Alt}{F4}")
                # automation.SendKey("{Ctrl}{Enter}")
                # automation.SendKey("{Alt}{F4}")
                break
        item.Click()
        time.sleep(0.5)
        automation.SendKeys('{Down}')
        time.sleep(0.5)
    return

    searchEdit = automation.FindControl(
        qqWindow, lambda c: (isinstance(c, automation.EditControl) or
                             isinstance(c, automation.ComboBoxControl)) and c.
        Name == 'Enter your search term')
    searchEdit.Click()
    automation.SendKeys(
        'Python-UIAutomation-for-Windows site:github.com{Enter}', 0.05)
    link = automation.HyperlinkControl(
        searchFromControl=qqWindow,
        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 = automation.TabItemControl(
        searchFromControl=tab,
        SubName='yinkaisheng/Python-UIAutomation-for-Windows')
    newTab.Click()
    starButton = automation.ButtonControl(searchFromControl=qqWindow,
                                          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)
        qqWindow.SetActive()
        time.sleep(1)
        starButton.Click()
        time.sleep(2)