def test(): auto.Logger.WriteLine('\nget screen size dpi unaware:', auto.ConsoleColor.DarkGreen) print(auto.GetScreenSize(False)) auto.Logger.WriteLine('\nget screen size dpi aware per monitor:', auto.ConsoleColor.DarkGreen) print(auto.GetScreenSize(True)) auto.Logger.WriteLine('\nget virtual screen size dpi unaware:', auto.ConsoleColor.DarkGreen) print(auto.GetVirtualScreenSize(False)) auto.Logger.WriteLine('\nget virtual screen size dpi per monitor:', auto.ConsoleColor.DarkGreen) print(auto.GetVirtualScreenSize(True)) auto.Logger.WriteLine('\nget monitors rect dpi unaware:', auto.ConsoleColor.DarkGreen) for rect in auto.GetMonitorsRect(False): print(rect) auto.Logger.WriteLine('\nget monitors rect dpi per monitor:', auto.ConsoleColor.DarkGreen) for rect in auto.GetMonitorsRect(True): print(rect) input('\nPress Enter to exit')
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 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()
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
def demo(): consoleWindow = auto.GetConsoleWindow() consoleWindow.SetActive() auto.Logger.ColorfullyWriteLine( '\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.' ) time.sleep(2) auto.ShowDesktop() # 打开notepad subprocess.Popen('notepad') # 查找notepad, 如果name有中文,python2中要使用Unicode notepad = auto.WindowControl(searchDepth=1, ClassName='Notepad', RegexName='.* - 记事本') # 可以判断window是否存在,如果不判断,找不到window的话会抛出异常 # if window.Exists(maxSearchSeconds = 3): if auto.WaitForExist(notepad, 3): auto.Logger.WriteLine("Notepad exists now") else: auto.Logger.WriteLine("Notepad does not exist after 3 seconds", auto.ConsoleColor.Yellow) screenWidth, screenHeight = auto.GetScreenSize() notepad.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2, screenHeight // 2) notepad.SetActive() # 查找edit # or edit = window.EditControl() edit = auto.EditControl(searchFromControl=notepad) edit.Click(waitTime=0) # python2中要使用Unicode, 模拟按键 edit.GetValuePattern().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') notepad.CaptureToImage('Notepad.png') edit.SendKeys('Image Notepad.png was captured, you will see it later.', 0.05) # 查找菜单 notepad.MenuItemControl(Name='格式(O)').Click() notepad.MenuItemControl(Name='字体(F)...').Click() windowFont = notepad.WindowControl(Name='字体') listItem = windowFont.ListControl( searchDepth=2, AutomationId='1000').ListItemControl(Name='微软雅黑') if listItem.Exists(2): listItem.GetScrollItemPattern().ScrollIntoView() listItem.Click() windowFont.ComboBoxControl(AutomationId='1140').Select('中文 GB2312') windowFont.ButtonControl(Name='确定').Click() notepad.GetWindowPattern().Close() if auto.WaitForDisappear(notepad, 3): auto.Logger.WriteLine("Notepad closed") else: auto.Logger.WriteLine("Notepad still exists after 3 seconds", auto.ConsoleColor.Yellow) # buttonNotSave = ButtonControl(searchFromControl = window, SubName = '不保存') # buttonNotSave.Click() # or send alt+n to not save and quit # auto.SendKeys('{Alt}n') # 使用另一种查找方法 buttonNotSave = notepad.ButtonControl( Compare=lambda control, depth: '不保存' in control.Name or '否' in control. Name) buttonNotSave.Click() subprocess.Popen('Notepad.png', shell=True) time.sleep(2) consoleWindow.SetActive() auto.Logger.WriteLine('script exits', auto.ConsoleColor.Cyan) time.sleep(2)
def testNotepadEN(): consoleWindow = auto.GetConsoleWindow() consoleWindow.SetActive() auto.Logger.ColorfullyWriteLine('\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.') time.sleep(2) auto.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 = auto.WindowControl(searchDepth=1, ClassName='Notepad', RegexName='.* - Notepad') # if window.Exists(maxSearchSeconds = 3): #check before using it if auto.WaitForExist(window, 3): auto.Logger.WriteLine("Notepad exists now") else: auto.Logger.WriteLine("Notepad does not exist after 3 seconds", auto.ConsoleColor.Yellow) screenWidth, screenHeight = auto.GetScreenSize() window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2, screenHeight // 2) window.SetActive() edit = auto.EditControl(searchFromControl=window) # or edit = window.EditControl() edit.Click(waitTime=0) edit.GetValuePattern().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') comboIndex = 0 selectIndex = 2 def select3rd(itemText: str): nonlocal comboIndex if comboIndex == selectIndex: return True comboIndex = comboIndex + 1 combo = windowFont.ComboBoxControl(AutomationId='1140') combo.Select(condition=select3rd) combo.Select('Western') windowFont.ButtonControl(Name='OK').Click() window.Close() if auto.WaitForDisappear(window, 3): auto.Logger.WriteLine("Notepad closed") else: auto.Logger.WriteLine("Notepad still exists after 3 seconds", auto.ConsoleColor.Yellow) # buttonNotSave = ButtonControl(searchFromControl = window, Name = 'Don\'t Save') # buttonNotSave.Click() # or send alt+n to not save and quit # auto.SendKeys('{Alt}n') # another way to find the button using lambda buttonNotSave = window.ButtonControl(Compare=lambda control, depth: 'Don\'t Save' in control.Name or 'No' in control.Name) buttonNotSave.Click() subprocess.Popen('Notepad.png', shell=True) time.sleep(2) consoleWindow.SetActive() auto.Logger.WriteLine('script exits', auto.ConsoleColor.Cyan) time.sleep(2)