def openDevelopmentMode(): runProgram('ms-settings:developers') settings = Desktop(backend="uia")["Settings"] btn = settings['For developersGroupBox'].RadioButton3 btn.click() settings['Use developer featuresDialog'].Yes.click() settings.close()
def __init__(self, app: QApplication, origin_draw_position: QPoint): """ Locate a desktop window rectangle with the mouse cursor :param QApplication app: App to install event filter on :param QPoint origin_draw_position: Position of the line, indicating the tracked cursor, is drawn from """ super(FindDesktopWindowInteractive, self).__init__() self.app = app self.tracking_timer = QTimer() self.tracking_timer.setInterval(self.tracking_rate) self.tracking_timer.timeout.connect(self._track_cursor) self.paint_timer = QTimer() self.paint_timer.setInterval(self.painting_rate) self.paint_timer.timeout.connect(self._trigger_paint) self.cursor = QCursor() self.pywin_desktop = Desktop() self.highlight_rect = QRect() self.origin_draw_pos = origin_draw_position # -- Transparent widget across the desktop to draw on -- self.desk_draw_widget = DesktopDrawWidget(app.desktop()) self.desk_draw_widget.paintEvent = self._paint_event_override
def mysql_installation(): # Loading the app exe file from the directory. ''' pywinauto dialogue select best name for the dialgoue combination. more details can be found here. https://pywinauto.readthedocs.io/en/latest/getting_started.html#attribute-resolution-magic https://pywinauto.readthedocs.io/en/latest/wait_long_operations.html :return: ''' app = Application(backend="uia").start("setups/wampserver.exe") # selecting the language dialogue box. Wizard = Desktop(backend='uia').Select_Setup_Language Wizard.OK.click_input() # app.InstallDialog.IAgreeRadioButton.wait('ready', timeout=30).click_input() Wizard2 = Desktop(backend='uia').Setup_Wampserver64 Wizard2.i_accept_the_agreement.click_input() Wizard2.NextButton.click_input() Wizard2.NextButton.click_input() Wizard2.NextButton.click_input() Wizard2.Install.click_input() # waiting for open dialogue to be closed Wizard2.wait_not('visible') # After installation, start the application from the windows installed directory start_wamp() time.sleep(5) # setup the database. This batch file created database in the db MySQL and improt all the sql file data into it. os.startfile(os.getcwd() + '/setups/database.bat')
def makeWorkingAppInstance(self, commandList): # helper pipe to flush popen self.DEVNULL = open(os.devnull, 'w') # get the hwnds of windows now desktopInstance = Desktop(backend="win32") hwnds = [] for window in desktopInstance.windows(): # get the hwnd as an int hwnds.append(int(window.handle)) # start the instance now # sill be used many times throughout this function appInstance = Application(backend="win32") # first things first, lets try to create one from scratch self.pid = subprocess.Popen(commandList, stdout=self.DEVNULL).pid appInstance.connect(process=self.pid) if len(appInstance.windows()) != 0: # the app we created has some windows, we are done self.usedExisting = True self.mainWindow = appInstance.top_window() self.mainWindow.wait("enabled") # It worked return True else: # maybe use best_match=commandList[0].split(".")[0] # we have to search through existing windows # TODO no new windows appear for some reason for window in desktopInstance.windows(): if int(window.handle) not in hwnds: self.usedExisting = False self.mainWindow = window # break out of function return True # if it reached here, nothing has been found return False
def stopTestApp(): print('Stop TestApp VPN...') dlg = Desktop(backend="uia").HydraTestAppShell # C:\Program Files (x86)\Hydra Test Application>taskkill /im "TestApp.exe" /f dlg.child_window(auto_id='DisconnectVpnBtn', control_type="Button").click() time.sleep(10)
def tray_click(button_text: str): systray = Desktop(backend='uia').taskbar.child_window( title_re='.*Notification Area') for btn in systray.buttons(): if btn.window_text() == button_text: btn.right_click_input() break else: raise ControlNotFound(button_text)
def start_from_tray(self, tray_icon): tray_icon.wrapper_object().click_input() tray_icon_menu = Desktop(backend="uia").window( **self.configs['TaskBar']['teacher_menu']['id']) tray_icon_menu.wait('visible', timeout=10) tray_icon_menu.window(**self.configs['TaskBar']['teacher_menu'] ['display_win']).wrapper_object().click_input() main_win = Desktop(backend="uia").window( **self.configs['teachermain']['main']['id']) main_win.exists(timeout=5)
def find_main_window(name, wait=True): desktop = Desktop() main_window = desktop.window(best_match=name) if wait: main_window.wait("visible") main_window.print_control_identifiers() return main_window
def click_enter_workspace(self): ''' 点击【作业空间】 :return: ''' # 点击【作业空间】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnWorkspace']].click() Workspace_win = Desktop(backend="uia").window( **self.configs['workspace']['id']) Workspace_win.wait('visible', timeout=30)
def click_enter_portal(self): ''' 点击【云校园】 :return: ''' # 点击【云校园】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnPortabl']].click() IvyCloud_win = Desktop(backend="uia").window( **self.configs['portal']['id']) IvyCloud_win.wait('visible', timeout=30)
def tray_menuclick(auto_id: str): tray_click('OnScreen Control') menu = Desktop(backend='uia').dialog.menu for item in menu.items(): if item.automation_id() == auto_id: item.click_input() break else: raise ControlNotFound(auto_id)
def calDemo(self): app = Application(backend="uia").start('calc.exe') dlg = Desktop(backend="uia").Calculator dlg.type_keys('2*3=') dlg.print_control_identifiers() dlg.minimize() Desktop(backend="uia").window(title='Calculator', visible_only=False).restore()
def start_lesson(self, lesson_name): ''' 上课 ''' # 点击【课程控制】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnLesson']].click() # 点击【上课】 self.click_menu_btn(self.configs['teachermain']['LessonMenu']['Start']) # 点击相应课程 self.click_lesson(lesson_name) lesson_win = Desktop(backend="uia").window( **self.configs['lesson_win']['id']) lesson_win.wait_not('visible', timeout=60)
class DesktopWindowSpecificationTests(unittest.TestCase): """Unit tests for Desktop object""" if UIA_support: def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Slow() self.app = Application().start('explorer.exe "' + mfc_samples_folder_32 + '"') self.desktop = Desktop(backend='uia') def tearDown(self): """Close the application after tests""" self.desktop.MFC_samplesDialog.CloseButton.click() self.desktop.MFC_samplesDialog.wait_not('visible') def test_folder_list(self): """Test that ListViewWrapper returns correct files list in explorer.exe""" files_list = self.desktop.MFC_samplesDialog.Shell_Folder_View.Items_View.wrapper_object( ) self.assertEqual( [item.window_text() for item in files_list.get_items()], [ u'x64', u'BCDialogMenu.exe', u'CmnCtrl1.exe', u'CmnCtrl2.exe', u'CmnCtrl3.exe', u'CtrlTest.exe', u'mfc100u.dll', u'RebarTest.exe', u'RowList.exe', u'TrayMenu.exe' ]) self.assertEqual( files_list.item('RebarTest.exe').window_text(), 'RebarTest.exe') else: # Win32 def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Defaults() self.app = Application(backend='win32').start( os.path.join(mfc_samples_folder, u"CmnCtrl3.exe")) self.desktop = Desktop() def tearDown(self): """Close the application after tests""" self.desktop.window(title='Common Controls Sample', process=self.app.process).SendMessage( win32defines.WM_CLOSE) def test_simple_access_through_desktop(self): """Test that controls can be accessed by 4 levels of attributes""" dlg = self.desktop.window(title='Common Controls Sample', process=self.app.process) self.assertEqual(dlg.Pager.Toolbar.button_count(), 12)
def delete_study(dialog, study): dialog.child_window(title="Workspace", control_type="MenuItem").click_input() Desktop(backend="uia").Menu.child_window( title="Close Study", control_type="MenuItem").click_input() dialog.window(title=study, found_index=0).right_click_input() Desktop(backend="uia").Menu.child_window( title="Delete Study", control_type="MenuItem").click_input() dialog.child_window(title="Delete Enter", control_type="Button").click_input() return
def restart_lesson(self): # 点击【课程控制】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnLesson']].click() # 点击【重启】 self.click_menu_btn( self.configs['teachermain']['LessonMenu']['Restart']) lesson_win = Desktop(backend="uia").window( **self.configs['lesson_win']['id']) dialog_confirm = lesson_win.window( **self.configs['lesson_win']['confirm']['id']) dialog_confirm.window( **self.configs['lesson_win']['confirm']['ok']).click()
def click_switch_local_mode(self): # 点击【课程控制】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnLesson']].click() # 点击【本地考试模式】 self.click_menu_btn( self.configs['teachermain']['LessonMenu']['ExamMode']) lesson_win = Desktop(backend="uia").window( **self.configs['lesson_win']['id']) dialog_confirm = lesson_win.window( **self.configs['lesson_win']['confirm']['id']) dialog_confirm.window( **self.configs['lesson_win']['confirm']['ok']).click()
def click_class_over(self): # 点击【课程控制】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnLesson']].click() # 点击【放学】 self.click_menu_btn( self.configs['teachermain']['LessonMenu']['ClassOver']) lesson_win = Desktop(backend="uia").window( **self.configs['lesson_win']['id']) dialog_confirm = lesson_win.window( **self.configs['lesson_win']['confirm']['id']) dialog_confirm.window( **self.configs['lesson_win']['confirm']['ok']).click()
def stop_lesson(self): ''' 下课 ''' # 点击【课程控制】 self.main_win[self.configs['teachermain']['toolbar'] ['BtnLesson']].click() # 点击【下课】 self.click_menu_btn(self.configs['teachermain']['LessonMenu']['Stop']) # lesson_win = Desktop(backend="uia").window( **self.configs['lesson_win']['id']) dialog_confirm = lesson_win.window( **self.configs['lesson_win']['confirm']['id']) dialog_confirm.window( **self.configs['lesson_win']['confirm']['ok']).click()
def click_splitbutton(dialog, button): split_buttons = {"SAX LV Endocardial Contour": 6, "SAX LV Open Endocardial Contour": 6, "SAX LV Epicardial Contour": 7, "SAX LV Open Epicardial Contour": 7, "SAX Papillary Muscle Contour": 8, "SAX LV Exclude Area Contour": 8, "SAX Reference Point": 9, "SAX Inferior Reference Point": 9, "Line Contour": 10, "Freehand Contour": 10, "Curved Length Measurement": 10, "SAX RV Endocardial Contour": 11, "SAX RV Epicardial Contour": 11, "SAX RV Papillary muscle Contour": 12, "SAX RV Exclude Area Contour": 12} if dialog.child_window(title=button).exists() is False: for filtered_button in [k for k, v in split_buttons.items() if v == split_buttons[button]]: if dialog.child_window(title=filtered_button).exists() is True: dialog.child_window(title=filtered_button).right_click_input() Desktop(backend="uia").Menu.child_window(title=button, control_type="MenuItem").click_input() else: dialog.child_window(title=button).click_input() dialog.progressbar.exists() return
def __job__(): # Gets all open windows, runs through the list of excluded programs and sorts by visibility windows = Desktop(backend="uia").windows() windowList = ([w.window_text() for w in windows]) ExcludeFromList.__remove__(windowList) Visibility.__notMinimized__(windowList) # Checks for ammount of monitors monitorLen = len(monitors) # Checks if a new window has been opened or a window has been closed if len(windowList) == numWindow and len(monitors) == monitorLen: #null = 'null' print('Number of window stays the same') else: numWindow = len(windowList) # Updates the number of open windows print("List length: " + str(len(windowList))) # Additional checks when running in IDE for program in windowList: Window = gw.getWindowsWithTitle(program)[0] print(Window) windowList = tuple(windowList) # Arranges windows depending on number of connected monitors count = 0 while count <= 3: if monitorLen == 1: ResizeSingle.__resize__(windowList) count += 1 if monitorLen == 2: ResizeDual.__resize__(windowList) count += 1
def test1001_anonymize_study(dialog, study, anon_name, filename): if dialog.child_window(title="Toolbar", control_type="ToolBar").\ child_window(title="Patient List", control_type="Button").exists() is True: dialog.child_window(title="Toolbar", control_type="ToolBar").child_window( title="Patient List", control_type="Button").click_input() dialog.Edit.set_text(study) dialog.window(title=study).right_click_input() Desktop(backend="uia").Menu.child_window( title="Anonymize Study", control_type="MenuItem").click_input() dialog.child_window(title="Anonymize", control_type="Window").Edit.set_text(anon_name) dialog.child_window(title="Anonymize", control_type="Window").OKEnter.click_input() start = time.time() dialog.child_window(title="Import Study done", control_type="StatusBar").wait('visible', 10000) or \ dialog.child_window(title="Load image previews done", control_type="StatusBar").wait('visible', 10000) end = time.time() print "Time to anonymize study: %.2f" % (end - start) outputFile.print_timing(1001, end - start, filename) return anon_name
def foreGroundDiscord( self): # it will make discord window top of all other windows windows = Desktop(backend="uia").windows() title = "" for w in windows: if "Discord" in str(w.window_text): title = str(w.window_text).split("'")[1] break app = None try: app = Application().connect(title_re=title) except (__import__("re").error, pywinauto.findwindows.ElementAmbiguousError): raise GuiDoesNotExists return hwin = app.top_window() hwin.set_focus() sleep(0.9)
def handle_dismiss(title, dlgwd): # handles the alert that happens in this specific case and dismisses it. Handle is to be tailored to its specific job. TODO: Maybe more functionality dlg = Desktop(backend="uia")['%s' %title] dlg[dlgwd].set_focus() #dlg.restore() keyboard.SendKeys("{VK_ESCAPE}") print "handle-function finished"
def close_aoe(): dlg = Desktop(backend="win32").window(title_re=game_title) left, top, right, bot = getrect(dlg.handle) focus_and_click(game_title, right - left - 20, 10) time.sleep(1) focus_and_click(game_title, (750 / 1680) * (right - left), (580 / 1050) * (bot - top - 20))
def add_file(self, file_path): """添加文件""" app = Desktop() dialog = app['打开'] time.sleep(2) dialog["Edit"].type_keys(file_path) dialog["Button"].click()
def get_url_from_active_tab(): # Ищем окно у которого в классе встречается Chrome chrome_app = Desktop(backend="uia").window(class_name_re='Chrome') # Получаем wrapper_object строки с юрл address_bar_wrapper = chrome_app['Google Chrome'].main.Edit.wrapper_object( ) url_from_browser = address_bar_wrapper.legacy_properties()['Value'] return url_from_browser
def runEdgeDevTools(): os.system( r'C:\Windows\SystemApps\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\MicrosoftEdgeDevToolsClientBeta.appx' ) install = Desktop(backend="uia")["App Installer"] install['Install Microsoft Edge DevTools Client? Install'].click() time.sleep(60) install.CloseButton.click()
def startCalcDialog() -> Application(): "This method just returns a Calculator dialog" app = Application(backend='uia').start('calc.exe') # needed since the application spaws additional processes # windows = Desktop(backend='uia').windows() # for w in windows: # print(w.window_text()) return Desktop(backend='uia').Calculator
def pegar_nome(self): janelas = Desktop(backend="uia").windows() janelas = [w.window_text() for w in janelas] for nome in janelas: if nome.find('Talisman Online | ') != -1: self.nome_do_processo = nome break
def testClickCustomizeButton(self): "Test click on the 'show hidden icons' button" # Minimize to tray self.dlg.minimize() _wait_minimized(self.dlg) # Make sure that the hidden icons area is enabled orig_hid_state = _toggle_notification_area_icons( show_all=False, debug_img="%s_01" % (self.id()) ) # Run one more instance of the sample app # hopefully one of the icons moves into the hidden area app2 = Application() app2.start(os.path.join(mfc_samples_folder, u"TrayMenu.exe")) dlg2 = app2.top_window() dlg2.wait('visible', timeout=self.tm) dlg2.minimize() _wait_minimized(dlg2) # Test click on "Show Hidden Icons" button taskbar.ShowHiddenIconsButton.click_input() niow_dlg = taskbar.explorer_app.window(class_name='NotifyIconOverflowWindow') niow_dlg.OverflowNotificationAreaToolbar.wait('ready', timeout=self.tm) niow_dlg.SysLink.click_input() nai = Desktop().window( title="Notification Area Icons", class_name="CabinetWClass" ) nai.wait('ready') origAlwaysShow = nai.CheckBox.get_check_state() if not origAlwaysShow: nai.CheckBox.click_input() nai.OK.click() # Restore Notification Area settings _toggle_notification_area_icons(show_all=orig_hid_state, debug_img="%s_02" % (self.id())) # close the second sample app dlg2.send_message(win32defines.WM_CLOSE)
class DesktopWindowSpecificationTests(unittest.TestCase): """Unit tests for Desktop object""" if UIA_support: def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Slow() self.app = Application().start('explorer.exe "' + mfc_samples_folder_32 + '"') self.desktop = Desktop(backend='uia') def tearDown(self): """Close the application after tests""" self.desktop.MFC_samplesDialog.CloseButton.click() self.desktop.MFC_samplesDialog.wait_not('visible') def test_folder_list(self): """Test that ListViewWrapper returns correct files list in explorer.exe""" files_list = self.desktop.MFC_samplesDialog.Shell_Folder_View.Items_View.wrapper_object() self.assertEqual([item.window_text() for item in files_list.get_items()], [u'x64', u'BCDialogMenu.exe', u'CmnCtrl1.exe', u'CmnCtrl2.exe', u'CmnCtrl3.exe', u'CtrlTest.exe', u'mfc100u.dll', u'RebarTest.exe', u'RowList.exe', u'TrayMenu.exe']) self.assertEqual(files_list.item('RebarTest.exe').window_text(), 'RebarTest.exe') else: # Win32 def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Defaults() self.app = Application(backend='win32').start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe")) self.desktop = Desktop() def tearDown(self): """Close the application after tests""" self.desktop.window(title='Common Controls Sample', process=self.app.process).SendMessage(win32defines.WM_CLOSE) def test_simple_access_through_desktop(self): """Test that controls can be accessed by 4 levels of attributes""" dlg = self.desktop.window(title='Common Controls Sample', process=self.app.process) self.assertEqual(dlg.Pager.Toolbar.button_count(), 12)
""" Example script for Calculator on Windows 10 Requirements: - Windows 10 - pywinauto 0.6.1+ Win10 version of Calculator is very specific. Few different processes (!) own different windows and controls, so the full hierarchy can be accessed through Desktop object only. Minimized Calculator is a process in a "Suspended" state. But it can be restored with some trick for invisible main window. """ from pywinauto import Desktop, Application app = Application(backend="uia").start('calc.exe') dlg = Desktop(backend="uia").Calculator dlg.type_keys('2*3=') dlg.print_control_identifiers() dlg.minimize() Desktop(backend="uia").window(title='Calculator', visible_only=False).restore()
def _toggle_notification_area_icons(show_all=True, debug_img=None): """ A helper function to change 'Show All Icons' settings. On a succesful execution the function returns an original state of 'Show All Icons' checkbox. The helper works only for an "English" version of Windows, on non-english versions of Windows the 'Notification Area Icons' window should be accessed with a localized title" """ Application().start(r'explorer.exe') class_name = 'CabinetWClass' def _cabinetwclass_exist(): "Verify if at least one active 'CabinetWClass' window is created" l = findwindows.find_elements(active_only=True, class_name=class_name) return (len(l) > 0) wait_until(_ready_timeout, _retry_interval, _cabinetwclass_exist) handle = findwindows.find_elements(active_only=True, class_name=class_name)[-1].handle window = WindowSpecification({'handle': handle, 'backend': 'win32', }) explorer = Application().connect(process=window.process_id()) cur_state = None try: # Go to "Control Panel -> Notification Area Icons" cmd_str = r'control /name Microsoft.NotificationAreaIcons' for _ in range(3): window.wait("ready", timeout=_ready_timeout) window.AddressBandRoot.click_input() explorer.wait_cpu_usage_lower(threshold=2, timeout=_ready_timeout) window.type_keys(cmd_str, with_spaces=True, set_foreground=True) # verfiy the text in the address combobox after type_keys finished cmbx_spec = window.AddressBandRoot.ComboBoxEx if cmbx_spec.exists(timeout=_ready_timeout, retry_interval=_retry_interval): texts = cmbx_spec.texts() if texts and texts[0] == cmd_str: break # Send ESCs to remove the invalid text window.type_keys("{ESC}" * 3) # Send 'ENTER' separately, this is to make sure # the window focus hasn't accidentally been lost window.type_keys( '{ENTER}', with_spaces=True, set_foreground=True ) explorer.wait_cpu_usage_lower(threshold=5, timeout=_ready_timeout) # Get the new opened applet notif_area = Desktop().window(title="Notification Area Icons", class_name=class_name) notif_area.wait("ready", timeout=_ready_timeout) cur_state = notif_area.CheckBox.get_check_state() # toggle the checkbox if it differs and close the applet if bool(cur_state) != show_all: notif_area.CheckBox.click_input() notif_area.Ok.click_input() explorer.wait_cpu_usage_lower(threshold=5, timeout=_ready_timeout) except Exception as e: if debug_img: from PIL import ImageGrab ImageGrab.grab().save("%s.jpg" % (debug_img), "JPEG") l = pywinauto.actionlogger.ActionLogger() l.log("RuntimeError in _toggle_notification_area_icons") raise e finally: # close the explorer window window.close() return cur_state
#M4S2 ('M', '4', 'S', '2') .wmv #MP43 ('M', 'P', '4', '3') .wmv #MPG1 ('M', 'P', 'G', '1') .wmv #MSS1 ('M', 'S', 'S', '1') .wmv #MSS2 ('M', 'S', 'S', '2') .wmv #WMV1 ('W', 'M', 'V', '1') .wmv #WMV2 ('W', 'M', 'V', '2') .wmv #WMV3 ('W', 'M', 'V', '3') .wmv #WVC1 ('W', 'V', 'C', '1') .wmv #mp4v ('m', 'p', '4', 'v') .mov if __name__ == '__main__': time.sleep(1) Popen('calc.exe', shell=True) dlg = Desktop(backend="uia")[u"電卓"] dlg.wait('visible') #spec_app = dlg.top_window() print(type(dlg)) # なぜか録画ができない time.sleep(3) th_cl = TestThread(dlg) #th_cl = TestThread(spec_app) th_cl.start() for i in [0,8,0,9,6,6,7,2,2,2,2]: numFile = u".\\numdata\\" + str(i) + u".png" print( numFile ) # p = pyautogui.locateOnScreen(numFile) #print(p)
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Defaults() self.app = Application(backend='win32').start(os.path.join(mfc_samples_folder, u"CmnCtrl3.exe")) self.desktop = Desktop()
def setUp(self): """Set some data and ensure the application is in the state we want""" Timings.Slow() self.app = Application().start('explorer.exe "' + mfc_samples_folder_32 + '"') self.desktop = Desktop(backend='uia')
from pywinauto import Desktop, Application Application().start('explorer.exe "C:\\Program Files"') # connect to another process spawned by explorer.exe app = Application(backend="uia").connect(path="explorer.exe", title="Program Files") app.ProgramFiles.set_focus() common_files = app.ProgramFiles.ItemsView.get_item('Common Files') common_files.right_click_input() app.ContextMenu.Properties.invoke() # this dialog is open in another process (Desktop object doesn't rely on any process id) Properties = Desktop(backend='uia').Common_Files_Properties Properties.print_control_identifiers() Properties.Cancel.click() Properties.wait_not('visible') # make sure the dialog is closed