def main(): firefoxWindow = automation.WindowControl(searchDepth=1, ClassName='MozillaWindowClass') if not firefoxWindow.Exists(0): automation.Logger.WriteLine('please run Firefox first', automation.ConsoleColor.Yellow) return firefoxWindow.ShowWindow(automation.ShowWindow.Maximize) firefoxWindow.SetActive() time.sleep(1) tab = firefoxWindow.TabControl() newTabButton = tab.ButtonControl(searchDepth=1) newTabButton.Click() edit = firefoxWindow.EditControl() # edit.Click() edit.SendKeys( 'http://global.bing.com/?rb=0&setmkt=en-us&setlang=en-us{Enter}') time.sleep(2) searchEdit = automation.FindControl( firefoxWindow, lambda c, d: (isinstance(c, automation.EditControl) or isinstance(c, automation.ComboBoxControl)) and c.Name == 'Enter your search term') # searchEdit.Click() searchEdit.SendKeys( 'Python-UIAutomation-for-Windows site:github.com{Enter}', 0.05) link = firefoxWindow.HyperlinkControl( SubName='yinkaisheng/Python-UIAutomation-for-Windows') automation.Win32API.PressKey(automation.Keys.VK_CONTROL) link.Click() #press control to open the page in a new tab automation.Win32API.ReleaseKey(automation.Keys.VK_CONTROL) newTab = tab.TabItemControl( SubName='yinkaisheng/Python-UIAutomation-for-Windows') newTab.Click() starButton = firefoxWindow.ButtonControl(Name='Star this repository') if starButton.Exists(5): automation.GetConsoleWindow().SetActive() automation.Logger.WriteLine( 'Star Python-UIAutomation-for-Windows after 2 seconds', automation.ConsoleColor.Yellow) time.sleep(2) firefoxWindow.SetActive() time.sleep(1) starButton.Click() time.sleep(2) else: unstarButton = firefoxWindow.ButtonControl( Name='Unstar this repository') if unstarButton.Exists(0, 0): automation.GetConsoleWindow().SetActive() automation.Logger.WriteLine('Thank you. You have starred.', automation.ConsoleColor.Yellow)
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 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 main(): th = threading.currentThread() auto.Logger.WriteLine( 'This is running in main thread. {} {}'.format(th.ident, th.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(th.ident, th.name), auto.ConsoleColor.Cyan)
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 _uiobj = auto.UIAutomationInitializerInThread(debug=True) 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.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 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() for listItem in allListItems: automation.Logger.WriteLine(listItem.Name) answer = input('是否获取详细信息?按y和Enter继续\n') 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): 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(listItem.Name, automation.ConsoleColor.Green) automation.Logger.WriteLine(GetPersonDetail()) listItem.Click() automation.SendKeys('{Down}')
automation.Win32API.PressKey(automation.Keys.VK_CONTROL) link.Click() #press control to open the page in a new tab automation.Win32API.ReleaseKey(automation.Keys.VK_CONTROL) newTab = tab.TabItemControl( SubName='yinkaisheng/Python-UIAutomation-for-Windows') newTab.Click() starButton = firefoxWindow.ButtonControl(Name='Star this repository') if starButton.Exists(5): automation.GetConsoleWindow().SetActive() automation.Logger.WriteLine( 'Star Python-UIAutomation-for-Windows after 2 seconds', automation.ConsoleColor.Yellow) time.sleep(2) firefoxWindow.SetActive() time.sleep(1) starButton.Click() time.sleep(2) else: unstarButton = firefoxWindow.ButtonControl( Name='Unstar this repository') if unstarButton.Exists(0, 0): automation.GetConsoleWindow().SetActive() automation.Logger.WriteLine('Thank you. You have starred.', automation.ConsoleColor.Yellow) if __name__ == '__main__': main() automation.GetConsoleWindow().SetActive() input('press Enter to exit')
def DemoCN(): """for Chinese language""" thisWindow = automation.GetConsoleWindow() automation.Logger.ColorfulWrite( '我将运行<Color=Cyan>cmd</Color>并设置它的<Color=Cyan>屏幕缓冲区</Color>使<Color=Cyan>cmd</Color>一行能容纳很多字符\n\n' ) time.sleep(3) automation.SendKeys('{Win}r') while not isinstance(automation.GetFocusedControl(), automation.EditControl): time.sleep(1) automation.SendKeys('cmd{Enter}') cmdWindow = automation.WindowControl(SubName='cmd.exe') cmdWindow.TitleBarControl().RightClick() automation.SendKey(automation.Keys.VK_P) optionWindow = cmdWindow.WindowControl(SubName='属性') optionWindow.TabItemControl(SubName='选项').Click() optionTab = optionWindow.PaneControl(SubName='选项') checkBox = optionTab.CheckBoxControl(AutomationId='103') while checkBox.CurrentToggleState() != automation.ToggleState.On: checkBox.Click() checkBox = optionTab.CheckBoxControl(AutomationId='104') while checkBox.CurrentToggleState() != automation.ToggleState.On: checkBox.Click() optionWindow.TabItemControl(SubName='布局').Click() layoutTab = optionWindow.PaneControl(SubName='布局') layoutTab.EditControl(AutomationId='301').SetValue('300') layoutTab.EditControl(AutomationId='303').SetValue('3000') layoutTab.EditControl(AutomationId='305').SetValue('140') layoutTab.EditControl(AutomationId='307').SetValue('30') optionWindow.ButtonControl(AutomationId='1').Click() cmdWindow.SetActive() l, t, r, b = cmdWindow.BoundingRectangle automation.DragDrop(l + 50, t + 10, 50, 10) thisWindow.SetActive() automation.Logger.ColorfulWrite( '我将运行<Color=Cyan>记事本</Color>并输入<Color=Cyan>Hello!!!</Color>\n\n') time.sleep(3) subprocess.Popen('notepad') notepadWindow = automation.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = automation.Win32API.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 0, cx // 2, cy // 2) time.sleep(0.5) notepadWindow.EditControl().SendKeys('Hello!!!', 0.05) time.sleep(1) dir = os.path.dirname(__file__) scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py')) thisWindow.SetActive() automation.Logger.ColorfulWrite( '运行"<Color=Cyan>automation.py -h</Color>"显示帮助\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() automation.Logger.ColorfulWrite( '运行"<Color=Cyan>automation.py -r -d1</Color>"显示所有顶层窗口, 即桌面的子窗口\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() automation.Logger.ColorfulWrite( '运行"<Color=Cyan>automation.py -c</Color>"显示鼠标光标下的控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() automation.Logger.ColorfulWrite( '运行"<Color=Cyan>automation.py -a</Color>"显示鼠标光标下的控件和它的所有父控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() automation.Logger.ColorfulWrite( '运行"<Color=Cyan>automation.py</Color>"显示当前激活窗口和它的所有子控件\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.EditControl().Click() time.sleep(3) cmdWindow.SetActive(waitTime=2) time.sleep(3) thisWindow.SetActive() automation.Logger.WriteLine('演示结束,按Enter退出', automation.ConsoleColor.Green) input()
def DemoEN(): """for other language""" thisWindow = automation.GetConsoleWindow() automation.Logger.ColorfulWrite('I will run <Color=Cyan>cmd</Color>\n\n') time.sleep(3) automation.SendKeys('{Win}r') while not isinstance(automation.GetFocusedControl(), automation.EditControl): time.sleep(1) automation.SendKeys('cmd{Enter}') cmdWindow = automation.WindowControl(SubName='cmd.exe') l, t, r, b = cmdWindow.BoundingRectangle automation.DragDrop(l + 50, t + 10, 50, 10) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'I will run <Color=Cyan>Notepad</Color> and type <Color=Cyan>Hello!!!</Color>\n\n' ) time.sleep(3) subprocess.Popen('notepad') notepadWindow = automation.WindowControl(searchDepth=1, ClassName='Notepad') cx, cy = automation.Win32API.GetScreenSize() notepadWindow.MoveWindow(cx // 2, 0, cx // 2, cy // 2) time.sleep(0.5) notepadWindow.EditControl().SendKeys('Hello!!!', 0.05) time.sleep(1) dir = os.path.dirname(__file__) scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py')) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'run "<Color=Cyan>automation.py -h</Color>" to display the help\n\n') time.sleep(3) cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'run "<Color=Cyan>automation.py -r -d1</Color>" to display the top level windows, desktop\'s children\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05) time.sleep(3) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'run "<Color=Cyan>automation.py -c</Color>" to display the control under mouse cursor\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'run "<Color=Cyan>automation.py -a</Color>" to display the control under mouse cursor and its ancestors\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.MoveCursorToMyCenter() time.sleep(3) cmdWindow.SetActive(waitTime=2) thisWindow.SetActive() automation.Logger.ColorfulWrite( 'run "<Color=Cyan>automation.py</Color>" to display the active window\n\n' ) time.sleep(3) cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05) notepadWindow.SetActive() notepadWindow.EditControl().Click() time.sleep(3) cmdWindow.SetActive(waitTime=2) time.sleep(3) thisWindow.SetActive() automation.Logger.WriteLine('press Enter to exit', automation.ConsoleColor.Green) input()
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 testNotepadEN(): consoleWindow = automation.GetConsoleWindow() consoleWindow.SetActive() automation.Logger.ColorfulWriteLine( '\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.' ) time.sleep(2) automation.ShowDesktop() subprocess.Popen('notepad') #search notepad window, if searchFromControl is None, search from RootControl #searchDepth = 1 makes searching faster, only searches RootControl's children, not children's children window = automation.WindowControl(searchDepth=1, ClassName='Notepad', SubName='Untitled - Notepad') #if window.Exists(maxSearchSeconds = 3): #check before using it if automation.WaitForExist(window, 3): automation.Logger.WriteLine("Notepad exists now") else: automation.Logger.WriteLine("Notepad does not exist after 3 seconds", automation.ConsoleColor.Yellow) screenWidth, screenHeight = automation.Win32API.GetScreenSize() window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2, screenHeight // 2) window.SetActive() edit = automation.EditControl( searchFromControl=window) #or edit = window.EditControl() edit.Click(waitTime=0) edit.SetValue('hi你好') edit.SendKeys('{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2, 0) edit.SendKeys(text) edit.SendKeys('{Enter 3}0123456789{Enter}', waitTime=0) edit.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}', waitTime=0) edit.SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}', waitTime=0) edit.SendKeys('`~!@#$%^&*()-_=+{Enter}', waitTime=0) edit.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}{Ctrl}a') window.CaptureToImage('Notepad.png') edit.SendKeys('Image Notepad.png was captured, you will see it later.', 0.05) #find menu window.MenuItemControl(Name='Format').Click() window.MenuItemControl(Name='Font...').Click() windowFont = window.WindowControl(Name='Font') windowFont.ComboBoxControl(AutomationId='1140').Select('Western') windowFont.ButtonControl(Name='OK').Click() window.Close() if automation.WaitForDisappear(window, 3): automation.Logger.WriteLine("Notepad closed") else: automation.Logger.WriteLine("Notepad still exists after 3 seconds", automation.ConsoleColor.Yellow) # buttonNotSave = ButtonControl(searchFromControl = window, Name = 'Don\'t Save') # buttonNotSave.Click() # or send alt+n to not save and quit # automation.SendKeys('{Alt}n') # another way to find the button using lambda buttonNotSave = automation.FindControl( window, lambda control, depth: control.ControlType == automation. ControlType.ButtonControl and 'Don\'t Save' == control.Name) buttonNotSave.Click() subprocess.Popen('Notepad.png', shell=True) time.sleep(2) consoleWindow.SetActive() automation.Logger.WriteLine('script exits', automation.ConsoleColor.Cyan) time.sleep(2)
def testNotepadCN(): consoleWindow = automation.GetConsoleWindow() consoleWindow.SetActive() automation.Logger.ColorfulWriteLine( '\nI will open <Color=Green>Notepad</Color> and <Color=Yellow>automate</Color> it. Please wait for a while.' ) time.sleep(2) automation.ShowDesktop() #打开notepad subprocess.Popen('notepad') #查找notepad, 如果name有中文,python2中要使用Unicode window = automation.WindowControl(searchDepth=1, ClassName='Notepad', SubName='无标题 - 记事本') #可以判断window是否存在,如果不判断,找不到window的话会抛出异常 #if window.Exists(maxSearchSeconds = 3): if automation.WaitForExist(window, 3): automation.Logger.WriteLine("Notepad exists now") else: automation.Logger.WriteLine("Notepad does not exist after 3 seconds", automation.ConsoleColor.Yellow) screenWidth, screenHeight = automation.Win32API.GetScreenSize() window.MoveWindow(screenWidth // 4, screenHeight // 4, screenWidth // 2, screenHeight // 2) window.SetActive() #查找edit edit = automation.EditControl( searchFromControl=window) #or edit = window.EditControl() edit.Click(waitTime=0) #python2中要使用Unicode, 模拟按键 edit.SetValue('hi你好') edit.SendKeys('{Ctrl}{End}{Enter}下面开始演示{! 4}{ENTER}', 0.2, 0) edit.SendKeys(text) edit.SendKeys('{Enter 3}0123456789{Enter}', waitTime=0) edit.SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{ENTER}', waitTime=0) edit.SendKeys('abcdefghijklmnopqrstuvwxyz{ENTER}', waitTime=0) edit.SendKeys('`~!@#$%^&*()-_=+{ENTER}', waitTime=0) edit.SendKeys('[]{{}{}}\\|;:\'\",<.>/?{ENTER}', waitTime=0) edit.SendKeys( '™®①②③④⑤⑥⑦⑧⑨⑩§№☆★○●◎◇◆□℃‰€■△▲※→←↑↓〓¤°#&@\^_―♂♀{ENTER}{CTRL}a') window.CaptureToImage('Notepad.png') edit.SendKeys('Image Notepad.png was captured, you will see it later.', 0.05) #查找菜单 window.MenuItemControl(Name='格式(O)').Click() window.MenuItemControl(Name='字体(F)...').Click() windowFont = window.WindowControl(Name='字体') windowFont.ComboBoxControl(AutomationId='1140').Select('中文 GB2312') windowFont.ButtonControl(Name='确定').Click() window.Close() if automation.WaitForDisappear(window, 3): automation.Logger.WriteLine("Notepad closed") else: automation.Logger.WriteLine("Notepad still exists after 3 seconds", automation.ConsoleColor.Yellow) # buttonNotSave = ButtonControl(searchFromControl = window, SubName = '不保存') # buttonNotSave.Click() # or send alt+n to not save and quit # automation.SendKeys('{Alt}n') # 使用另一种查找方法 buttonNotSave = automation.FindControl( window, lambda control, depth: control.ControlType == automation. ControlType.ButtonControl and '不保存' in control.Name) buttonNotSave.Click() subprocess.Popen('Notepad.png', shell=True) time.sleep(2) consoleWindow.SetActive() automation.Logger.WriteLine('script exits', automation.ConsoleColor.Cyan) time.sleep(2)