def exportToFile(self, days): """ 点击导出 :param Name: 标签元素名称 :param Depth: 空间深度 :param foundIndex: 同种类控件序列号 :return: 页签控件 """ try: # 触发导出保存界面 Name = "导出" Depth = 22 foundIndex = 3 co = ControlOperation() flag = uiautomation.ButtonControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() time.sleep(60) # 配置保存路径 # TODO 优化:判定路径是否存在,不存在则创建 filePath = EXPORTPATH file = uiautomation.EditControl(AutomationId="1001") fileName = uiautomation.EditControl( AutomationId="1001").GetValuePattern().Value date = datetime.datetime.now().strftime("%Y%m%d") fileName = filePath + date + "_" + days + fileName + str( time.time()) co.give_value(file, fileName) except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def test(): subprocess.Popen(path) automation.WindowControl(class_name='Qt5QWindowIcon', Name='userLoginViewClass').Refind(20, 1) window = automation.WindowControl(searchDepth=1, ClassName='Qt5QWindowIcon', Name=u'userLoginViewClass') # 用户名 edit1 = automation.EditControl(searchFromControl=window, Name=u'lineEdit_userName') edit1.DoubleClick() PressKey(0x0E) key_input('guojian') # 密码 edit2 = automation.EditControl(searchFromControl=window, Name=u'lineEdit_password') edit2.DoubleClick() key_input('8888888888888') # 验证码 edit3 = automation.EditControl(searchFromControl=window, Name=u'lineEdit_identifyCode') edit3.DoubleClick() key_input('izxf') # 确定 button = automation.ButtonControl(searchFromControl=window, Name=u'pushButton_sure') button.Click()
def batchImportChoose(self, fileName=None, name="", Depth=None, foundIndex=None, winChooseID=""): """ 触发批量导入 :param fileName: 需要导入的文件名称 :param name: 导入窗口的路径选择空间名称 :param Depth: 导入窗口的路径选择空间深度 :param foundIndex: 导入窗口的路径选择空间序列 :param winChooseID: 系统自带路径输入框的AutomationID :return: """ co = ControlOperation() try: flag = uiautomation.EditControl(name=name, Depth=Depth, foundIndex=foundIndex) flag.Click() file = uiautomation.EditControl(AutomationId=winChooseID) # a = "C:\\Users\\user\\PycharmProjects\\Tools\\EZAccessScenesAutoConfig\\Data\\Person\\Info\\cn002.xls" co.give_value(file, fileName) return True except Exception as e: log.debug("Can not control EZAccess, because: %s" % e) return False
def setBodyTemperatureE(self, TemperatureS, Name="", Depth=22, foundIndex=4): """ 选中体温起始框 :param Name: 标签元素名称 :param Depth: 空间深度 :param foundIndex: 同种类控件序列号 :return: 页签控件 """ TemperatureS = str(TemperatureS) try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() pos = autoit.mouse_get_pos() time.sleep(1) autoit.mouse_click(button="left", x=pos[0] + 70, y=pos[1], clicks=1, speed=100) self.co.give_value(value=TemperatureS) # autoit.send(TemperatureS) except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def SendKeysByEditClassName(self, classname, keys): try: sleep(2) el = automation.EditControl(ClassName=classname) el.SendKeys(keys) except Exception as e: print("输入值异常" + '||原因:' + str(e))
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 input_text(self, field, message, num): while 1: try: search = auto.EditControl(AutomationId='SearchFrame') search.SendKeys('{Ctrl}a{Delete}') self._log.info('搜索字段:{}'.format(field)) search.SendKeys(field + '{Enter}') try: fieldInput = self._CaseShowTwoPO.getTab6()( Name=field).GetParentControl().GetChildren()[2] fieldInput.DoubleClick() time.sleep(self.clickout) send = fieldInput.EditControl() self._log.info('填写字段:{}-->{}'.format(field, message)) send.SendKeys('{Ctrl}a{Delete}') send.SendKeys(message + '{Enter}') except LookupError: self._log.error('案例序号:{},字段:{},名称有误,请检查'.format( num, field)) return False, field break except Exception as e: tab = auto.TabControl(AutomationId='mainTab').TabItemControl( Name='emd.ViewModel.ColGridViewModel') tab.DoubleClick() self._log.error(f"输入对象丢失,正在重新查找,报错信息为{e}") continue
def portal_yct(self): '''第一次跳转到登录页''' result = automation.EditControl( Depth=11, Name='开办企业申请信息填写人需进行实名认证,系统将跳转至“一网通办”总门户进行用户注册和认证') if automation.WaitForExist(result, 5): automation.HyperlinkControl(Depth=10, Name='确定').Click() return 1 else: raise ('portal_yct异常')
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)
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 setting_onex(phone_num, password_onex, CM_server): Setting_general = uiautomation.WindowControl(Name = "WindowSettingsGeneral") Setting_general.SetFocus() # add Extension extension = Setting_general.EditControl(ClassName = "TextBox") extension.SetFocus() extension.SendKeys('{Ctrl}' '{A}') extension.SendKeys('{DEL}') extension.SendKeys(phone_num) #add password pass_onex = uiautomation.EditControl(ClassName = "PasswordBox") pass_onex.SetFocus() pass_onex.SendKeys('{Ctrl}' '{A}') pass_onex.SendKeys('{DEL}') pass_onex.SendKeys(password_onex) # Clean old Server IP list_server = Setting_general.ListControl(AutomationID="ListBoxControllers") list_server.SetFocus() child_list_server = Setting_general.ListItemControl(Name="onexcui.ViewModel.WindowControllerViewModel") # remove all old server while child_list_server.Exists(3): child_list_server.Click() btn_remove = Setting_general.ButtonControl(Name="Remove") btn_remove.Click() #add server IP #click add button btn_add = Setting_general.ButtonControl(Name = "Add") btn_add.Click() #add IP Window_add = uiautomation.WindowControl(Name = "Add Server") Window_add.SetFocus() add_CM = Window_add.EditControl(ClassName = "TextBox") add_CM.SendKeys(CM_server) #click ok btn_ok_ip = Window_add.ButtonControl(ClassName = "Button") btn_ok_ip.SetFocus() btn_ok_ip.Click() while uiautomation.WindowControl(Name="WindowMessageBox").Exists(3): uiautomation.WindowControl(Name="WindowMessageBox").ButtonControl(Name="OK").Click() #click OK_General Setting Setting_general = uiautomation.WindowControl(Name = "WindowSettingsGeneral") Setting_general.SetFocus() btn_ok = Setting_general.ButtonControl(Name = "OK") btn_ok.SetFocus() btn_ok.Click() while uiautomation.WindowControl(Name="WindowMessageBox").Exists(3): uiautomation.WindowControl(Name="WindowMessageBox").ButtonControl(Name="OK").Click()
def keyWord(self, Name="关键字", Depth=13, foundIndex=1): """ 搜索框内输入假日关键字 :return: """ try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def get_edit_control(self, loc): try: if loc[0] == Wby.NAME: edit_control = auto.EditControl(searchDepth=loc[2], Name=loc[1]) logger.info("深度为_{}_,名字为_{}__的edit_control获取成功".format( loc[2], loc[1])) return edit_control if loc[0] == Wby.AUTOMATIONID: edit_control = auto.EditControl(searchDepth=loc[2], AutomationId=loc[1]) logger.info("深度为_{}_,id为_{}__的edit_control获取成功".format( loc[2], loc[1])) return edit_control except: if loc[0] == Wby.NAME: logger.exception("深度为_{}_,名字为_{}__的edit_control获取失败".format( loc[2], loc[1])) if loc[0] == Wby.AUTOMATIONID: logger.exception("深度为_{}_,名字为_{}__的edit_control获取失败".format( loc[2], loc[1]))
def test_gitgui(): # Clone폴더 값 정의 clone_folder = "C:\\dev\\git\\UIAutomationExample" # Clone 대상 폴더가 존재할 경우 폴더를 지운다. import os if os.path.exists(clone_folder): os.system('rmdir /S /Q "{}"'.format(clone_folder)) # Clone 대상 폴더가 없는지 확인한다. if os.path.exists(clone_folder): assert False, "clone대상폴더가 지워지지 않음" # GIT GUI를 실행시킨다. import uiautomation as auto # 검색영역 클릭하기 auto.ButtonControl(searchDepth=3, Name='검색하려면 여기에 입력하십시오.').Click() # 검색영역에 값 입력하기 auto.EditControl(searchDepth=3, Name='검색 상자').SendKeys('git gui') # Git GUI아이콘 클릭하기 auto.TextControl(searchDepth=10, Name="Git GUI").Click() # 프로그램이 정상적으로 수행되었는지 확인한다. auto.WindowControl(searchDepth=1, Name="Git Gui") # 상단 메뉴를 통해 Clone을 수행 auto.MenuItemControl(searchDepth=8, Name="Repository").Click() auto.MenuItemControl(searchDepth=8, Name="Repository") # inspect를 통해서 menu의 AutomationId가 48이므로 이를 활용 auto.MenuItemControl(AutomationId = "48").Click() # 화면이 Clone Existing Repository 세부설정화면으로 이동되었는지 확인한다. # 아쉽게도 해당 APP은 "Clone Existing Repository"에 대한 정보를 확인할 수 없는 앱이어서 # 이후 동작으로 확인할 수 밖에 없다. # Source location 및 Target Directory 값 정의 source_location = "https://github.com/jjunghyup/UIAutomationExample.git" target_directory = "C:\\dev\\git\\UIAutomationExample" # Source Location값과 Target Directory값을 입력한다. auto.PaneControl(ClassName="TkChild", foundIndex=14).Click() auto.PaneControl(ClassName="TkChild", foundIndex=14).SendKeys(source_location) auto.PaneControl(ClassName="TkChild", foundIndex=11).Click() auto.PaneControl(ClassName="TkChild", foundIndex=11).SendKeys(target_directory) # 값이 정상적으로 입력된다. # 값을 Clipboard에 복사하고 붙여넣기 식으로 확인이 가능하지만 해당 내용은 이후에 작성 예정 # Clone 버튼을 클릭한다. auto.PaneControl(ClassName="TkChild", foundIndex=18).Click() # Clone 대상폴더가 존재하는지 확인한다. 10초 동안 확인한다. result = False for i in range(0, 10): if os.path.exists(clone_folder): result = True assert result, "clone대상폴더가 존재 하지 않음"
def test(): subprocess.Popen(path) automation.WindowControl(class_name='Qt5QWindowIcon', RegexName='userLoginView').Refind(20, 1) window = automation.WindowControl(searchDepth=1, ClassName='Qt5QWindowIcon', RegexName=u'userLoginView') # 用户名 edit1 = automation.EditControl(searchFromControl=window, foundIndex=1) edit1.DoubleClick() PressKey(0x0E) key_input('guojian') # 密码 edit2 = automation.EditControl(searchFromControl=window, foundIndex=2) edit2.DoubleClick() key_input('8888888888888') # 验证码 edit3 = automation.EditControl(searchFromControl=window, foundIndex=3) edit3.DoubleClick() key_input('izxf') # 确定 button = automation.ButtonControl(searchFromControl=window, Name=u'确定') button.Click()
def checkProgress(self, name="", Depth=None, foundIndex=None): while True: time.sleep(1) try: flag = uiautomation.EditControl(name=name, Depth=Depth, foundIndex=foundIndex) print(flag) if flag: flag = False print(flag) else: break except: break
def personSearch(self, Name="请输入关键字", Depth=22, foundIndex=1): """ 选中人员筛选框 :param Name: 标签元素名称 :param Depth: 空间深度 :param foundIndex: 同种类控件序列号 :return: 页签控件 """ try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def select(self, Name="", Depth=18, foundIndex=1): """ 点击,选择每页条数,20条/页,100条/页 :param Name: :param Depth: :param foundIndex: :return: """ try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() return flag except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def send_password(self, pwd, Name="密码", Depth=9, foundIndex=2): """ 登陆处填写密码 :param pwd: 用户名字符串 :param Name: 元素名称 :param Depth: 元素深度 :param foundIndex: 索引序列号 :return: 无 """ try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag = self.co.give_value(flag, pwd) log.info(str(flag.GetValuePattern().Value)) except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
def get_browser_tab_url(browser: str): """ Get browser tab url, browser must already open :param browser: Support 'Edge' 'Google Chrome' and other Chromium engine browsers :return: Current tab url """ if browser.lower() == 'edge': addr_bar = auto.EditControl(AutomationId='addressEditBox') else: win = auto.PaneControl(Depth=1, ClassName='Chrome_WidgetWin_1', SubName=browser) temp = win.PaneControl(Depth=1, Name=browser).GetChildren()[1].GetChildren()[0] for bar in temp.GetChildren(): last = bar.GetLastChildControl() if last and last.Name != '': break addr_bar = bar.GroupControl(Depth=1, Name='').EditControl() url = addr_bar.GetValuePattern().Value return url
def send_user_name(self, username, Name="用户名", Depth=9, foundIndex=1): """ 登陆处填写用户名 :param username: 用户名字符串 :param Name: 元素名称 :param Depth: 元素深度 :param foundIndex: 索引序列号 :return: 无 """ try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, foundIndex=foundIndex) flag = self.co.give_value(flag, username) log.info(str(flag.GetValuePattern().Value)) except Exception as e: # log.info("Can not control EZAccess, because: %s" % e) log.debug("Can not control EZAccess, because: %s" % e)
def setBodyTemperatureS(self, TemperatureS, Name="", Depth=22, foundIndex=4): """ 选中体温起始框,输入体温值 :param Name: 标签元素名称 :param Depth: 空间深度 :param foundIndex: 同种类控件序列号 :return: 页签控件 """ TemperatureS = str(TemperatureS) try: flag = uiautomation.EditControl(Name=Name, Depth=Depth, fondIndex=foundIndex) flag.Click() self.co.give_value(value=TemperatureS) except Exception as e: log.debug("Can not control EZAccess, because: %s" % e)
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)
#!python3 # -*- coding:utf-8 -*- import sys import subprocess import uiautomation as automation if __name__ == '__main__': isTop = 1 print(sys.argv) if len(sys.argv) == 2: isTop = int(sys.argv[1]) note = automation.WindowControl(searchDepth=1, ClassName='Notepad') if note.Exists(0, 0): note.SetTopmost(isTop) else: subprocess.Popen('notepad') note.Refind() note.SetTopmost(isTop) note.Move(0, 0) note.Resize(400, 300) edit = automation.EditControl(searchFromControl=note) edit.Click() automation.SendKeys('I\'m a topmost window!!!')
def ClickEditByClassName(self, classname): try: sleep(2) automation.EditControl(ClassName=classname).Click() except Exception as e: print("按钮点击异常" + '||原因:' + str(e))
def ClickEditByName(self, name): try: sleep(2) automation.EditControl(Name=name).Click() except Exception as e: print("编辑位置点击异常" + '||原因:' + str(e))
def editFileName(): return automation.EditControl(SubName="File name")
def RenameTreeItem(tree, treeItem, bookMarks, depth, removeChapter=True): treeItem.ScrollIntoView() if depth > TreeDepth: return name = treeItem.Name if not name.strip(): return newName, alert = RenameFunction(name, removeChapter) if newName.startswith('Appendix'): removeChapter = False bookMark = BookMark(name, newName) bookMarks.append(bookMark) if newName != name and depth not in TreeSkipDepthList: global Renamed Renamed = True time.sleep(0.1) find = False for i in range(3): treeItem.RightClick(simulateMove=False, waitTime=0.2) # FoxitReader书签右键菜单(BCGPToolBar,非Windows菜单)弹出后,枚举不到菜单,但从屏幕点上ControlFromPoint能获取到菜单, todo # 采用特殊处理获取重命名菜单 x, y = automation.Win32API.GetCursorPos() menuItem = automation.ControlFromPoint(x + 2, y + 2) if isinstance(menuItem, automation.MenuItemControl): #鼠标右下方弹出菜单 while 1: if menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename': find = True break y += 20 menuItem = automation.ControlFromPoint(x + 2, y) if not isinstance(menuItem, automation.MenuItemControl): break else: #鼠标右上方弹出菜单 menuItem = automation.ControlFromPoint(x + 2, y - 2) while 1: if menuItem.Name == '重命名(R)' or menuItem.Name == 'Rename': find = True break y -= 20 menuItem = automation.ControlFromPoint(x + 2, y) if not isinstance(menuItem, automation.MenuItemControl): break if find: break else: automation.SendKeys('{Esc}') time.sleep(0.5) if not find: automation.Logger.Log('this pdf not support editing') exit(0) menuItem.Click(simulateMove=False, waitTime=0.2) edit = automation.EditControl(searchFromControl=tree, searchDepth=1) edit.SetValue(newName, waitTime=0.05) automation.SendKeys('{Enter}', waitTime=0.05) automation.Logger.Write('rename: ') automation.Logger.WriteLine(name, automation.ConsoleColor.Green) automation.Logger.Write(' @@to : ' if alert else ' to: ') automation.Logger.WriteLine( newName, automation.ConsoleColor.Yellow if alert else automation.ConsoleColor.Green) if depth + 1 > TreeDepth: return if automation.ExpandCollapseState.Collapsed == treeItem.CurrentExpandCollapseState( ): treeItem.Expand(0.1) childItems = treeItem.GetChildren() if childItems: for child in childItems: RenameTreeItem(tree, child, bookMark.children, depth + 1, removeChapter)
def _geekbench4_run(): try: auto.WindowControl(searchDepth = 1,Name = 'Untitled - Geekbench 4 Pro').GetWindowPattern().Close() except: time.sleep(1) try: auto.WindowControl(searchDepth = 1,Name = 'Geekbench 4 Pro').GetWindowPattern().Close() except: time.sleep(1) run_path = 'C://Program Files (x86)//Geekbench 4//' os.chdir(run_path) os.system('start "" ".\Geekbench 4.exe"') """ ControlType: ButtonControl ClassName: CCPushButton AutomationId: CommandButton_101 Rect: (837,586,949,611)[112x25] Name: Enter License Handle: 0x90DA0(593312) Depth: 4 SupportedPattern: InvokePattern LegacyIAccessiblePattern """ time.sleep(2) i = 1 while(1): try: if auto.ButtonControl(Name = 'Run CPU Benchmark',searchDepth = 2,AutomationId = '120').Exists(): if auto.WindowControl(Name = 'Geekbench 4 Pro',searchDepth = 1).Exists(0.1): auto.ButtonControl(Name = 'Run CPU Benchmark',searchDepth = 2,AutomationId = '120').Click() break if auto.WindowControl(Name = 'Geekbench 4 Tryout',searchDepth = 1).Exists(0.1): auto.ButtonControl(Name = 'Enter License').Click() time.sleep(1) auto.EditControl(AutomationId = '1004',searchDepth = 4).Click() auto.EditControl(AutomationId = '1004',searchDepth = 4).SendKeys('*****@*****.**') auto.EditControl(AutomationId = '1006',searchDepth = 4).Click() auto.EditControl(AutomationId = '1006',searchDepth = 4).SendKeys('OTCRR-HDYE4-UPAJA-SJZPR-PSYTY-TUR3C-ECRZJ-QMJZF-3C6LE') auto.ButtonControl(Name = 'Unlock',searchDepth = 4).Click() auto.ButtonControl(searchDepth = 5, AutomationId = '2').Click() auto.WindowControl(Name = 'Geekbench 4 Tryout',searchDepth = 1).GetWindowPattern().Close() os.chdir(run_path) os.system('start "" "Geekbench 4.exe"') i = i+1 except: time.sleep(1) time.sleep(1) while(1): try: if not auto.WindowControl(Name = 'Benchmark Progress',searchDepth = 2).Exists(): break except: time.sleep(1) score_win = auto.PaneControl(Name = 'Geekbench Score',searchDepth = 6) result_dict = {} result_dict['Single-Core Score'] = score_win.TextControl(searchDepth = 7,foundIndex = 2).Name result_dict['Multi-Core Score'] = score_win.TextControl(searchDepth = 7,foundIndex = 4).Name time.sleep(10) auto.WindowControl(searchDepth = 1,Name = 'Untitled - Geekbench 4 Pro').GetWindowPattern().Close() auto.WindowControl(searchDepth = 1,Name = 'Geekbench 4 Pro').GetWindowPattern().Close() return result_dict
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)