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( 'https://www.bing.com/?rb=0&setmkt=en-us&setlang=en-us{Enter}') time.sleep(2) searchEdit = firefoxWindow.Control( Compare=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') try: automation.Win32API.PressKey(automation.Keys.VK_CONTROL) link.Click() #press control to open the page in a new tab except Exception as ex: automation.Win32API.ReleaseKey(automation.Keys.VK_CONTROL) raise 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)
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): 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() # 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)
def trainOld(): '''养号''' log('>>>> train() begin...') console = uiautomation.GetConsoleWindow() while True: window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() log('train begin window: {0}'.format(window.Handle)) # # 点击搜索 # uiautomation.Win32API.MouseClick(126, 24) # # 输入“文件传输助手” # window.SendKeys(u'文件传输助手') # # 点击联系人 # uiautomation.Win32API.MouseClick(147, 88) # 直接点击第一个联系人 uiautomation.Win32API.MouseClick(136, 73) # 输入url window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好你好!!!{Enter}') # 窗口放到最后 window.SendKeys('{ALT}{ESC}') log('train end window: {0}'.format(window.Handle)) time.sleep(1800) console.SetActive() log('>>>> train() end...')
def main(): auto.ShowDesktop() subprocess.Popen('notepad') time.sleep(1) note = auto.WindowControl(searchDepth=1, ClassName='Notepad') note.SetActive() note.SetTopmost() transformNote = note.GetTransformPattern() transformNote.Move(400, 0) transformNote.Resize(400, 300) edit = note.EditControl() edit.SendKeys('{Ctrl}{End}{Enter 2}I\'m a topmost window!!!\nI cover other windows.') subprocess.Popen('mmc.exe devmgmt.msc') mmcWindow = auto.WindowControl(searchDepth=1, ClassName='MMCMainFrame') mmcWindow.SetActive() transformMmc = mmcWindow.GetTransformPattern() transformMmc.Move(100, 100) transformMmc.Resize(400, 300) time.sleep(1) auto.DragDrop(160, 110, 900, 110, 0.2) auto.DragDrop(900, 110, 160, 110, 0.2) mmcWindow.SendKeys('{Alt}f', waitTime=1) mmcWindow.SendKeys('X', charMode=False) # or mmcWindow.SendKey(auto.Keys.VK_X) edit.SendKeys('{Ctrl}{End}{Enter 2}You close me.') vp = edit.GetValuePattern() if vp: print('current text:', vp.Value) auto.GetConsoleWindow().SetActive()
def refreshDict(): console = uiautomation.GetConsoleWindow() # new handle global nextHandleKey log('nextHandleKey = ' + str(nextHandleKey)) begHandle = 0 while True: window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') window.ShowWindow(uiautomation.ShowWindow.Maximize) #window.SetActive() curHandle = window.Handle if begHandle == 0 : begHandle = curHandle elif begHandle == curHandle : break if curHandle not in handleDict.values(): handleDict[nextHandleKey] = curHandle log('add: ' + str(nextHandleKey) + ' ' + str(curHandle)) nextHandleKey += 1 window.SendKeys('{ALT}{ESC}') console.SetActive() # invalid handle keyList = handleDict.copy().keys() for index in keyList: curHandle = handleDict[index] window = uiautomation.ControlFromHandle(curHandle) if window == None: handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) log('dice is refreshed: len=' + str(len(handleDict)) + ' nextHandleKey='+str(nextHandleKey))
def main(): consoleWindow = automation.GetConsoleWindow() print(consoleWindow) print('\nconsole window will be hidden in 3 seconds') time.sleep(3) consoleWindow.Hide() time.sleep(2) print('\nconsole window shows again') consoleWindow.Show()
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 #pass 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() # 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)
def record(url): '''录制''' console = uiautomation.GetConsoleWindow() window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() # 点击“文件传输助手”(要求置顶) uiautomation.Win32API.MouseClick(170, 75) window.SendKeys(4 * (url + ' ') + '{Enter}') uiautomation.Win32API.MouseClick(1130, 480) page = uiautomation.WindowControl(searchDepth=1, ClassName='IEWebViewWnd', SubName=u'微信') page.ShowWindow(uiautomation.ShowWindow.Maximize) page.SetActive() # 滚动到选项 v = page.PaneControl(ClassName='Internet Explorer_Server') clicks = [] while True: console.SetActive() # input(u'1.请把webview滚动到合适的未知,然后按回车: ') raw_input(u'1. scroll webview to proper percent, and press enter: ') percent = v.CurrentVerticalScrollPercent() print(percent) v.SetScrollPercent(0, percent) console.SetActive() # input(u'2.请把鼠标放在webview中需要点击的位置,然后按回车: ') c = raw_input(u'2. put cursor to proper position, and press enter: ') (x, y) = uiautomation.Win32API.GetCursorPos() print((x, y)) clicks.append((percent, x, y)) # c = input(u'3.还需要继续操作,请输入c并按回车:') b = raw_input( u'3. if want to break, input b and press enter, or press enter for exit: ' ) if b == 'b': break page.Close() print(clicks) # TODO wait votes = input('4. how many votes you want to do? ') action = { # 被认为是局部变量不会保存到全局变量中 'url': url, 'clicks': clicks, # TODO wait 'votes': votes } print('action: ') print(action)
def main(): main = threading.currentThread() auto.Logger.WriteLine('This is running in main thread. {} {}'.format(main.ident, main.name), auto.ConsoleColor.Cyan) time.sleep(2) auto.GetConsoleWindow().CaptureToImage('console_mainthread.png') root = auto.GetRootControl() auto.EnumAndLogControl(root, 1) th = threading.Thread(target=threadFunc, args=(root, )) th.start() th.join() auto.Logger.WriteLine('\nMain thread exits. {} {}'.format(main.ident, main.name), auto.ConsoleColor.Cyan)
def vote(url, count): '''投票''' global nextVoteIndex global voteIngFlag global handleDict log('vote() begin...') voteIngFlag = True console = uiautomation.GetConsoleWindow() while count > 0: if nextVoteIndex >= nextHandleKey: nextVoteIndex = 0 if nextVoteIndex not in handleDict.keys(): nextVoteIndex += 1 continue window = uiautomation.ControlFromHandle(handleDict[nextVoteIndex]) if window == None: log('Error: window not exist ' + str(nextVoteIndex) + ' ' + str(handleDict[nextVoteIndex]) + ', so pop it') log('pop: ' + str(nextVoteIndex) + ' ' + str(handleDict[nextVoteIndex])) handleDict.pop(nextVoteIndex) nextVoteIndex += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() # # 点击搜索 # uiautomation.Win32API.MouseClick(126, 24) # # 输入“文件传输助手” # window.SendKeys(u'文件传输助手') # # 点击联系人 # uiautomation.Win32API.MouseClick(147, 88) # 直接点击第一个联系人 uiautomation.Win32API.MouseClick(136, 73) log('click') # 输入url window.SendKeys(40 * '{Ctrl}{Enter}' + 4 * (url + ' ') + '{Enter}', interval=0) log('click1') # time.sleep(0.5) # 点击输入框的上面一行文字(要求刚输入的文字就贴在输入框上方),弹出webview或浏览器 uiautomation.Win32API.MouseClick(1661, 817) log('click2') time.sleep(0.5) # 做投票动作 # dovote3(window) # TODO 等待并截图,或者判断是否成功 count -= 1 # 窗口放到最后 window.SendKeys('{ALT}{ESC}') log('vote end window: ' + str(handleDict[nextVoteIndex])) nextVoteIndex += 1 console.SetActive() voteIngFlag = False log('vote() end...')
def main(): input('请先用Firefox登录钉钉,并在组织架构一级目录页面,脚本运行过程中可以按住F8暂停脚本,按F9恢复,现在按Enter键继续') consoleWindow = auto.GetConsoleWindow() consoleWindow.SetTopmost(True) sx, sy = auto.Win32API.GetScreenSize() consoleWindow.Move(0, sy // 2) consoleWindow.Resize(sx // 3, sy // 2 - 40) firefoxWindow = auto.WindowControl(searchDepth=1, ClassName='MozillaWindowClass') firefoxWindow.SetActive() firefoxWindow.SetWindowVisualState(auto.WindowVisualState.Maximized) doc = firefoxWindow.DocumentControl(searchDepth=4) Parse(doc)
def main(): width = 500 height = 500 cmdWindow = automation.GetConsoleWindow() automation.Logger.WriteLine('create a transparent image') bitmap = automation.Bitmap(width, height) bitmap.ToFile('image_transparent.png') cmdWindow.SetActive() automation.Logger.WriteLine('create a blue image') start = time.clock() for x in range(width): for y in range(height): argb = 0x0000FF | ((255 * x // 500) << 24) bitmap.SetPixelColor(x, y, argb) cost = time.clock() - start automation.Logger.WriteLine( 'write {}x{} image by SetPixelColor cost {:.3f}s'.format( width, height, cost)) bitmap.ToFile('image_blue.png') start = time.clock() for x in range(width): for y in range(height): bitmap.GetPixelColor(x, y) cost = time.clock() - start automation.Logger.WriteLine( 'read {}x{} image by GetPixelColor cost {:.3f}s'.format( width, height, cost)) start = time.clock() argb = [(0xFF0000 | (0x0000FF * y // height) | ((255 * x // width) << 24)) for x in range(width) for y in range(height)] bitmap.SetPixelColorsHorizontally(0, 0, argb) cost = time.clock() - start automation.Logger.WriteLine( 'write {}x{} image by SetPixelColorsHorizontally cost {:.3f}s'.format( width, height, cost)) bitmap.ToFile('image_red.png') start = time.clock() bitmap.GetAllPixelColors() cost = time.clock() - start automation.Logger.WriteLine( 'read {}x{} image by GetAllPixelColors cost {:.3f}s'.format( width, height, cost)) bitmap.ToFile('image_red.png') bitmap.ToFile('image_red.jpg') subprocess.Popen('image_red.png', shell=True)
def train(): log('>>>> train() begin...') console = uiautomation.GetConsoleWindow() index = 0 while True: if voteIngFlag: time.sleep(600) continue if index >= nextHandleKey: index = 0 if index not in handleDict.keys(): index += 1 continue window = uiautomation.ControlFromHandle(handleDict[index]) if window == None: log('Error: window not exist ' + str(index) + ' ' + str(handleDict[index]) + ', so pop it') handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) index += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() log('train begin: ' + str(handleDict[index]) + ' ' + str(index)) # 直接点击第1个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 73) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个A风筝的线条固阳A.{Enter}') # 直接点击第2个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 129) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个B风筝的线条固阳B.{Enter}') # 直接点击第3个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 181) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个C风筝的线条固阳C.{Enter}') # 直接点击第4个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 245) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个D风筝的线条固阳D.{Enter}') # 直接点击第5个联系人 time.sleep(3) uiautomation.Win32API.MouseClick(136, 317) # window.SendKeys(time.strftime('%Y-%m-%d %H:%M:%S')+' 你好想是个E风筝的线条固阳E.{Enter}') # 收尾窗口放到最后 window.SendKeys('{ALT}{ESC}') log('train end ' + str(handleDict[index]) + ' \n') index += 1 time.sleep(300) #1776 console.SetActive() log('>>>> train() end...')
def walk(): wiresharkWindow = None for win in auto.GetRootControl().GetChildren(): if win.ClassName == 'MainWindow' and win.AutomationId == 'MainWindow': if win.ToolBarControl( AutomationId='MainWindow.displayFilterToolBar').Exists( 0, 0): wiresharkWindow = win break if not wiresharkWindow: auto.Logger.WriteLine('Can not find Wireshark', auto.ConsoleColor.Yellow) return console = auto.GetConsoleWindow() if console: sx, sy = auto.GetScreenSize() tp = console.GetTransformPattern() tp.Resize(sx, sy // 4) tp.Move(0, sy - sy // 4 - 50) console.SetTopmost() wiresharkWindow.SetActive(waitTime=0.1) wiresharkWindow.Maximize() auto.Logger.ColorfullyWriteLine('Press <Color=Cyan>F1</Color> to stop', auto.ConsoleColor.Yellow) tree = wiresharkWindow.TreeControl(searchDepth=4, ClassName='PacketList', Name='Packet list') rect = tree.BoundingRectangle tree.Click(y=50, waitTime=0.1) auto.SendKeys('{Home}', waitTime=0.1) columnCount = 0 treeItemCount = 0 for item, depth in auto.WalkControl(tree): if isinstance(item, auto.HeaderControl): columnCount += 1 auto.Logger.Write(item.Name + ' ') elif isinstance(item, auto.TreeItemControl): if treeItemCount % columnCount == 0: auto.Logger.Write('\n') time.sleep(0.1) treeItemCount += 1 auto.Logger.Write(item.Name + ' ') if item.BoundingRectangle.bottom >= rect.bottom: auto.SendKeys('{PageDown}', waitTime=0.1) if auto.IsKeyPressed(auto.Keys.VK_F1): auto.Logger.WriteLine('\nF1 pressed', auto.ConsoleColor.Yellow) break
def main(): automation.Logger.WriteLine('请把鼠标放在QQ群聊天窗口中的一个成员上面,3秒后获取\n') time.sleep(3) listItem = automation.ControlFromCursor() if listItem.ControlType != automation.ControlType.ListItemControl: automation.Logger.WriteLine('没有放在群成员上面,程序退出!') return consoleWindow = automation.GetConsoleWindow() consoleWindow.SetActive() qqWindow = listItem.GetTopWindow() list = listItem.GetParentControl() allListItems = list.GetChildren() f=open(r'f:\resqq.txt','a') for listItem in allListItems: automation.Logger.WriteLine(listItem.Name) f.write(listItem.Name) f.close()
def threadFunc(root): """ If you want to use functionalities related to Controls and Patterns in a new thread. You must call InitializeUIAutomationInCurrentThread first in the thread and call UninitializeUIAutomationInCurrentThread when the thread exits. But you can't use use a Control or a Pattern created in a different thread. So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it. """ #print(root)# you cannot use root because it is root control created in main thread th = threading.currentThread() auto.Logger.WriteLine('\nThis is running in a new thread. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan) time.sleep(2) auto.InitializeUIAutomationInCurrentThread() auto.GetConsoleWindow().CaptureToImage('console_newthread.png') newRoot = auto.GetRootControl() #ok, root control created in new thread auto.EnumAndLogControl(newRoot, 1) auto.UninitializeUIAutomationInCurrentThread() auto.Logger.WriteLine('\nThread exits. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)
def main(): automation.Logger.WriteLine('请把鼠标放在QQ群聊天窗口中的一个成员上面,3秒后获取\n') time.sleep(3) listItem = automation.ControlFromCursor() if listItem.ControlType != automation.ControlType.ListItemControl: automation.Logger.WriteLine('没有放在群成员上面,程序退出!') return consoleWindow = automation.GetConsoleWindow() if consoleWindow: consoleWindow.SetActive() qqWindow = listItem.GetTopWindow() list = listItem.GetParentControl() allListItems = list.GetChildren() for listItem in allListItems: automation.Logger.WriteLine(listItem.Name) answer = 'y' if answer.lower() == 'y': automation.Logger.WriteLine('\n3秒后开始获取QQ群成员详细资料,您可以一直按住F10键暂停脚本') time.sleep(3) qqWindow.SetActive() #确保群里第一个成员可见在最上面 left, top, right, bottom = list.BoundingRectangle while allListItems[0].BoundingRectangle[1] < top: automation.Win32API.MouseClick(right - 5, top + 20) for listItem in allListItems: if listItem.ControlType == automation.ControlType.ListItemControl: if automation.Win32API.IsKeyPressed(automation.Keys.VK_F10): if consoleWindow: consoleWindow.SetActive() input('\n您暂停了脚本,按Enter继续\n') qqWindow.SetActive() 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('eachpersonstart') automation.Logger.WriteLine(listItem.Name, automation.ConsoleColor.Green) automation.Logger.WriteLine(GetPersonDetail()) listItem.Click() automation.SendKeys('{Down}')
def threadFunc(uselessRoot): """ If you want to use UI Controls in a new thread, create an UIAutomationInitializerInThread object first. But you can't use use a Control or a Pattern created in a different thread. So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it. """ # print(uselessRoot)# you cannot use uselessRoot because it is a control created in a different thread th = threading.currentThread() auto.Logger.WriteLine( '\nThis is running in a new thread. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan) time.sleep(2) with auto.UIAutomationInitializerInThread(debug=True): auto.GetConsoleWindow().CaptureToImage('console_newthread.png') newRoot = auto.GetRootControl( ) # ok, root control created in current thread auto.EnumAndLogControl(newRoot, 1) auto.Logger.WriteLine('\nThread exits. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)
def color(): console = uiautomation.GetConsoleWindow() index = 0 while True: if voteIngFlag: log('voteIngFlag ...') time.sleep(6) continue if index >= nextHandleKey: break if index not in handleDict.keys(): index += 1 continue window = uiautomation.ControlFromHandle(handleDict[index]) if window == None: log('Error: window not exist ' + str(index) + ' ' + str(handleDict[index]) + ', so pop it') handleDict.pop(index) log('pop: ' + str(index) + ' ' + str(curHandle)) index += 1 else: window.ShowWindow(uiautomation.ShowWindow.Maximize) window.SetActive() log('train begin: ' + str(handleDict[index]) + ' ' + str(index)) # 直接点击第1个联系人 time.sleep(3) log('...: ') uiautomation.Win32API.MouseClick(136, 73) print(uiautomation.Win32API.GetPixelColor(136,73,handleDict[index])) # 直接点击第2个联系人 time.sleep(3) log('...: ') uiautomation.Win32API.MouseClick(136, 129) print(uiautomation.Win32API.GetPixelColor(136,129,handleDict[index])) # 收尾窗口放到最后 index += 1 window.SendKeys('{ALT}{ESC}') log('train end window ' + str(handleDict[index]) + ' \n') log('end\n') time.sleep(10) console.SetActive() log('>>>> train() end...')
def voteOld(url, count): '''投票''' log('vote() begin...') console = uiautomation.GetConsoleWindow() while count > 0: window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') log('vote begin window: {0}'.format(window.Handle)) # window.ShowWindow(uiautomation.ShowWindow.Maximize) # window.ShowWindow(uiautomation.ShowWindow.Restore) # window.MoveWindow(0,0,850,590) window.SetActive(waitTime=0) log('setactive') # # 点击搜索 # uiautomation.Win32API.MouseClick(126, 24) # # 输入“文件传输助手” # window.SendKeys(u'文件传输助手') # # 点击联系人 # uiautomation.Win32API.MouseClick(147, 88) # 直接点击第一个联系人 uiautomation.Win32API.MouseClick(136, 73) log('click') # 输入url window.SendKeys(4 * (url + ' ') + '{Enter}', 0, 0) # 点击输入框的上面一行文字(要求刚输入的文字就贴在输入框上方),弹出webview或浏览器 uiautomation.Win32API.MouseClick(591, 346) # 做投票动作 # dovote3(window) # TODO 等待并截图,或者判断是否成功 count -= 1 # 窗口放到最后 window.SendKeys('{ALT}{ESC}') log('vote end window: {0}'.format(window.Handle)) console.SetActive() log('vote() end...')
def createDict(): console = uiautomation.GetConsoleWindow() global nextHandleKey global handleDict index = 0 handleDict.clear() while True: window = uiautomation.WindowControl(searchDepth=1, ClassName='WeChatMainWndForPC', SubName=u'微信') if not window.Exists(0): log('please open windown first') return window.ShowWindow(uiautomation.ShowWindow.Maximize) #window.SetActive() curHandle = window.Handle if curHandle in handleDict.values(): break else : handleDict[index] = curHandle log(str(index) + ' ' + str(curHandle)) index += 1 window.SendKeys('{ALT}{ESC}') console.SetActive() nextHandleKey = index log('dice is created: len=' + str(len(handleDict)) + ' nextHandleKey='+str(nextHandleKey))
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() edit.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() searchEdit.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)
type=int, dest='sampleRate', default=0, help='sample rate') parser.add_argument('-b', '--begin', type=int, dest='beginNo', default=0, help='begin no') parser.add_argument('-n', '--num', type=int, dest='maxPacket', default=0xFFFFFFFF, help='read packets count') parser.add_argument('-l', '--lost', type=bool, dest='calculateLost', default=False, help='calculate lost packets') args = parser.parse_args() cmdWindow = automation.GetConsoleWindow() cmdWindow.SetTopmost() if 0 == args.sampleRate: args.sampleRate = int(input('please input sample rate: ')) Analyze(args.sampleRate, args.beginNo, args.maxPacket, args.calculateLost) cmdWindow.SetActive() input('press enter to exit')
def main(): width = 500 height = 500 cmdWindow = auto.GetConsoleWindow() print('create a transparent image') bitmap = auto.Bitmap(width, height) bitmap.ToFile('image_transparent.png') cmdWindow.SetActive() print('create a blue image') start = auto.ProcessTime() for x in range(width): for y in range(height): argb = 0x0000FF | ((255 * x // 500) << 24) bitmap.SetPixelColor(x, y, argb) cost = auto.ProcessTime() - start print('write {}x{} image by SetPixelColor cost {:.3f}s'.format( width, height, cost)) bitmap.ToFile('image_blue.png') start = auto.ProcessTime() for x in range(width): for y in range(height): bitmap.GetPixelColor(x, y) cost = auto.ProcessTime() - start print('read {}x{} image by GetPixelColor cost {:.3f}s'.format( width, height, cost)) argb = [(0xFF0000 | (0x0000FF * y // height) | ((255 * x // width) << 24)) for x in range(width) for y in range(height)] start = auto.ProcessTime() bitmap.SetPixelColorsOfRect(0, 0, width, height, argb) cost = auto.ProcessTime() - start print( 'write {}x{} image by SetPixelColorsOfRect with List[int] cost {:.3f}s' .format(width, height, cost)) bitmap.ToFile('image_red.png') arrayType = auto.ctypes.c_uint32 * (width * height) nativeArray = arrayType(*argb) start = auto.ProcessTime() bitmap.SetPixelColorsOfRect(0, 0, width, height, nativeArray) cost = auto.ProcessTime() - start print( 'write {}x{} image by SetPixelColorsOfRect with native array cost {:.3f}s' .format(width, height, cost)) bitmap.ToFile('image_red2.png') start = auto.ProcessTime() colors = bitmap.GetAllPixelColors() cost = auto.ProcessTime() - start print('read {}x{} image by GetAllPixelColors cost {:.3f}s'.format( width, height, cost)) bitmap.ToFile('image_red.png') bitmap.ToFile('image_red.jpg') subprocess.Popen('image_red.png', shell=True) root = auto.GetRootControl() bitmap = root.ToBitmap(0, 0, 400, 400) print('save (0,0,400,400) of desktop to desk_part.png') bitmap.ToFile('desk_part.png') width, height = 100, 100 colors = bitmap.GetPixelColorsOfRects([(0, 0, width, height), (100, 100, width, height), (200, 200, width, height)]) for i, nativeArray in enumerate(colors): print('save part of desk_part.png to desk_part{}.png'.format(i)) with auto.Bitmap(width, height) as subBitmap: subBitmap.SetPixelColorsOfRect(0, 0, width, height, nativeArray) subBitmap.ToFile('desk_part{}.png'.format(i)) print('save part of desk_part.png to desk_part3.png') with bitmap.Copy(300, 300, 100, 100) as subBitmap: subBitmap.ToFile('desk_part3.png') print('flip X of desk_part.png') with bitmap.RotateFlip(auto.RotateFlipType.RotateNoneFlipX) as bmpFlipX: bmpFlipX.ToFile('desk_flipX.png') print('flip Y of desk_part.png') with bitmap.RotateFlip(auto.RotateFlipType.RotateNoneFlipY) as bmpFlipY: bmpFlipY.ToFile('desk_flipY.png') print('rotate 90 of desk_part.png') with bitmap.Rotate(90) as bmpRotate90: bmpRotate90.ToFile('desk_rotate90.png') print('rotate 270 of desk_part.png') with bitmap.Rotate(270) as bmpRotate270: bmpRotate270.ToFile('desk_rotate270.png') print('rotate 45 of desk_part.png') with bitmap.Rotate(45) as bmpRotate45: bmpRotate45.ToFile('desk_rotate45.png')
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) if __name__ == '__main__': main() automation.GetConsoleWindow().SetActive() input('press Enter to exit')
def DemoCN(): """for Chinese language""" thisWindow = auto.GetConsoleWindow() auto.Logger.ColorfullyWrite( '我将运行<Color=Cyan>cmd</Color>并设置它的<Color=Cyan>屏幕缓冲区</Color>使<Color=Cyan>cmd</Color>一行能容纳很多字符\n\n' ) time.sleep(3) auto.SendKeys('{Win}r') while not isinstance(auto.GetFocusedControl(), auto.EditControl): time.sleep(1) auto.SendKeys('cmd{Enter}') cmdWindow = auto.WindowControl(RegexName='.+cmd.exe') cmdWindow.TitleBarControl().RightClick() auto.SendKey(auto.Keys.VK_P) optionWindow = cmdWindow.WindowControl(SubName='属性') optionWindow.TabItemControl(SubName='选项').Click() optionTab = optionWindow.PaneControl(SubName='选项') checkBox = optionTab.CheckBoxControl(AutomationId='103') if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On: checkBox.Click() checkBox = optionTab.CheckBoxControl(AutomationId='104') if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On: checkBox.Click() optionWindow.TabItemControl(SubName='布局').Click() layoutTab = optionWindow.PaneControl(SubName='布局') layoutTab.EditControl(AutomationId='301').GetValuePattern().SetValue('300') layoutTab.EditControl( AutomationId='303').GetValuePattern().SetValue('3000') layoutTab.EditControl(AutomationId='305').GetValuePattern().SetValue('140') layoutTab.EditControl(AutomationId='307').GetValuePattern().SetValue('30') optionWindow.ButtonControl(AutomationId='1').Click() cmdWindow.SetActive() rect = cmdWindow.BoundingRectangle auto.DragDrop(rect.left + 50, rect.top + 10, 50, 30) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '我将运行<Color=Cyan>记事本</Color>并输入<Color=Cyan>Hello!!!</Color>\n\n') time.sleep(3) subprocess.Popen('notepad') notepadWindow = auto.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = auto.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 20, 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() auto.Logger.ColorfullyWrite( '运行"<Color=Cyan>automation.py -h</Color>"显示帮助\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() auto.Logger.ColorfullyWrite( '运行"<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() auto.Logger.ColorfullyWrite( '运行"<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() auto.Logger.ColorfullyWrite( '运行"<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() auto.Logger.ColorfullyWrite( '运行"<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() auto.Logger.WriteLine('演示结束,按Enter退出', auto.ConsoleColor.Green) input()
def DemoEN(): """for other language""" thisWindow = auto.GetConsoleWindow() auto.Logger.ColorfullyWrite('I will run <Color=Cyan>cmd</Color>\n\n') time.sleep(3) auto.SendKeys('{Win}r') while not isinstance(auto.GetFocusedControl(), auto.EditControl): time.sleep(1) auto.SendKeys('cmd{Enter}') cmdWindow = auto.WindowControl(SubName='cmd.exe') rect = cmdWindow.BoundingRectangle auto.DragDrop(rect.left + 50, rect.top + 10, 50, 10) thisWindow.SetActive() auto.Logger.ColorfullyWrite( 'I will run <Color=Cyan>Notepad</Color> and type <Color=Cyan>Hello!!!</Color>\n\n' ) time.sleep(3) subprocess.Popen('notepad') notepadWindow = auto.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = auto.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 20, 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() auto.Logger.ColorfullyWrite( '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() auto.Logger.ColorfullyWrite( '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() auto.Logger.ColorfullyWrite( '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() auto.Logger.ColorfullyWrite( '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() auto.Logger.ColorfullyWrite( '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() auto.Logger.WriteLine('press Enter to exit', auto.ConsoleColor.Green) input()
for handle in handles: win = auto.ControlFromHandle(handle) win.Show(0) if auto.IsIconic(handle): win.ShowWindow(auto.SW.Restore, 0) if __name__ == '__main__': for i in range(2): subprocess.Popen('notepad.exe') time.sleep(1) notepad = auto.WindowControl(searchDepth=1, ClassName='Notepad') notepad.MoveWindow(i * 400, 0, 400, 300) notepad.SendKeys('notepad {}'.format(i + 1)) auto.SetConsoleTitle('Hide: Ctrl+1, Show: Ctrl+2, Exit: Ctrl+D') cmdWindow = auto.GetConsoleWindow() if cmdWindow: cmdWindow.GetTransformPattern().Move(0, 300) auto.Logger.ColorfullyWriteLine( 'Press <Color=Green>Ctr+1</Color> to hide the windows\nPress <Color=Green>Ctr+2</Color> to show the windows\n' ) handles = [ win.NativeWindowHandle for win in auto.GetRootControl().GetChildren() if win.ClassName in WindowsWantToHide ] auto.RunByHotKey( { (auto.ModifierKey.Control, auto.Keys.VK_1): lambda event: hide(event, handles), (auto.ModifierKey.Control, auto.Keys.VK_2): lambda event: show(event, handles),
break stopEvent.wait(0.01) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--main', action='store_true', help='exec main') parser.add_argument('--hide', action='store_true', help='hide window') parser.add_argument('--show', action='store_true', help='show window') args = parser.parse_args() if args.main: if args.hide: hide() elif args.show: show() else: subprocess.Popen('notepad') auto.GetConsoleWindow().SetActive() auto.Logger.ColorfullyWriteLine( 'Press <Color=Green>Ctr+1</Color> to hide\nPress <Color=Green>Ctr+2</Color> to show\n' ) auto.RunByHotKey( { (auto.ModifierKey.Control, auto.Keys.VK_1): lambda e: HotKeyFunc(e, ['--main', '--hide']), (auto.ModifierKey.Control, auto.Keys.VK_2): lambda e: HotKeyFunc(e, ['--main', '--show']), }, (auto.ModifierKey.Control, auto.Keys.VK_9))
def main(): sw, sh = auto.GetScreenSize() cmdWindow = auto.GetConsoleWindow() if cmdWindow: cmdTransformPattern = cmdWindow.GetTransformPattern() cmdTransformPattern.Move(sw // 2, 0) cmdTransformPattern.Resize(sw // 2, sh * 3 // 4) subprocess.Popen('mmc.exe devmgmt.msc') mmcWindow = auto.WindowControl(searchDepth=1, ClassName='MMCMainFrame') mmcTransformPattern = mmcWindow.GetTransformPattern() mmcTransformPattern.Move(0, 0) mmcTransformPattern.Resize(sw // 2, sh * 3 // 4) tree = mmcWindow.TreeControl() for item, depth in auto.WalkControl(tree, includeTop=True): if isinstance( item, auto.TreeItemControl ): #or item.ControlType == auto.ControlType.TreeItemControl item.GetSelectionItemPattern().Select(waitTime=0.05) pattern = item.GetExpandCollapsePattern() if pattern.ExpandCollapseState == auto.ExpandCollapseState.Collapsed: pattern.Expand(waitTime=0.05) auto.Logger.WriteLine(' ' * (depth - 1) * 4 + item.Name, auto.ConsoleColor.Green) if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll by <Color=Cyan>SetScrollPercent</Color>') cmdWindow.SetActive(waitTime=1) mmcWindow.SetActive(waitTime=1) treeScrollPattern = tree.GetScrollPattern() treeScrollPattern.SetScrollPercent(auto.ScrollPattern.NoScrollValue, 0) treeScrollPattern.SetScrollPercent(auto.ScrollPattern.NoScrollValue, 100) if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll to top by SendKeys <Color=Cyan>Ctrl+Home</Color>') cmdWindow.SetActive(waitTime=1) mmcWindow.SetActive(waitTime=1) tree.SendKeys('{Ctrl}{Home}', waitTime=1) if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll to bottom by SendKeys <Color=Cyan>Ctrl+End</Color>') cmdWindow.SetActive(waitTime=1) mmcWindow.SetActive(waitTime=1) tree.SendKeys('{Ctrl}{End}', waitTime=1) if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll to top by <Color=Cyan>WheelUp</Color>') cmdWindow.SetActive(waitTime=1) print(tree.NativeWindowHandle, tree.Element, len(tree.GetChildren())) # before expand, tree has no scrollbar. after expand, tree has a scrollbar. # need to Refind on some PCs before find ScrollBarControl from tree # maybe the old element has no scrollbar info tree.Refind() print(tree.NativeWindowHandle, tree.Element, len(tree.GetChildren())) vScrollBar = tree.ScrollBarControl( AutomationId='NonClientVerticalScrollBar') rangeValuePattern = vScrollBar.GetRangeValuePattern() vScrollBarRect = vScrollBar.BoundingRectangle thumb = vScrollBar.ThumbControl() while True: vPercent = treeScrollPattern.VerticalScrollPercent vPercent2 = rangeValuePattern.Value print('ScrollPattern.VerticalScrollPercent', vPercent) print('ValuePattern.Value', vPercent2) if vPercent2 > 0: tree.WheelUp(waitTime=0.05) else: break if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll to bottom by <Color=Cyan>WheelDown</Color>') cmdWindow.SetActive(waitTime=1) while True: vPercent = treeScrollPattern.VerticalScrollPercent vPercent2 = rangeValuePattern.Value print('ScrollPattern.VerticalScrollPercent', vPercent) print('ValuePattern.Value', vPercent2) if vPercent2 < 100: tree.WheelDown(waitTime=0.05) else: break if cmdWindow: auto.Logger.ColorfullyWriteLine( 'Scroll by <Color=Cyan>DragDrop</Color>') cmdWindow.SetActive(waitTime=1) mmcWindow.SetActive(waitTime=1) x, y = thumb.MoveCursorToMyCenter() auto.DragDrop(x, y, x, vScrollBarRect.top, waitTime=1) x, y = thumb.MoveCursorToMyCenter() auto.DragDrop(x, y, x, vScrollBarRect.bottom) mmcWindow.GetWindowPattern().Close() if cmdWindow: cmdWindow.SetActive() auto.Logger.Write('\nPress any key to exit', auto.ConsoleColor.Cyan) import msvcrt while not msvcrt.kbhit(): pass