def test_connect_windowspec(self): """Test that connect_() works with a windowspec""" app1 = Application() app1.start(_notepad_exe()) #unused var: handle = app1.UntitledNotepad.handle app_conn = Application() try: app_conn.connect(title="Untitled - Notepad") except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only=True, title="Untitled - Notepad") app_conn.connect(handle=wins[0].handle) except findwindows.ElementNotFoundError: WaitUntil( 30, 0.5, lambda: len( findwindows.find_elements(active_only=True, title="Untitled - Notepad")) > 0) wins = findwindows.find_elements(active_only=True, title="Untitled - Notepad") app_conn.connect(handle=wins[0].handle) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def loginView(self): try: connected_nordlocker.connect(title='NordLocker') except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) except findwindows.ElementNotFoundError: wait_until(30, 0.5, lambda: len(findwindows.find_elements(active_only=True, title="NordLocker")) > 0) wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle)
def find_elements(self, locator, *args): by, value = self.format_locator(locator, *args) if by == "title": return findwindows.find_elements(title=value) elif by == "title_re": return findwindows.find_elements(title_re=value) elif by == "class_name": return findwindows.find_elements(class_name=value) elif by == "class_name_re": return findwindows.find_elements(class_name_re=value) else: self.log.warning("%s is not support when find elements" % by)
def test_wait_cpu_usage_lower(self): """Test that wait_cpu_usage_lower() works correctly""" if is_x64_Python() != is_x64_OS(): return None Application().Start(r'explorer.exe') def _cabinetwclass_exist(): "Verify if at least one active 'CabinetWClass' window is created" l = findwindows.find_elements(active_only=True, class_name='CabinetWClass') return (len(l) > 0) WaitUntil(40, 0.5, _cabinetwclass_exist) handle = findwindows.find_elements( active_only=True, class_name='CabinetWClass')[-1].handle window = WindowSpecification({ 'handle': handle, 'backend': 'win32', }) explorer = Application().Connect(process=window.process_id()) try: explorer.WaitCPUUsageLower(threshold=1.5, timeout=60, usage_interval=2) window.AddressBandRoot.ClickInput() window.TypeKeys(r'Control Panel\Programs\Programs and Features', with_spaces=True, set_foreground=True) window.TypeKeys(r'{ENTER}', set_foreground=False) WaitUntil( 40, 0.5, lambda: len( findwindows.find_elements(active_only=True, title='Programs and Features', class_name='CabinetWClass')) > 0) explorer.WaitCPUUsageLower(threshold=1.5, timeout=60, usage_interval=2) installed_programs = window.FolderView.texts()[1:] programs_list = ','.join(installed_programs) if ('Microsoft' not in programs_list) and ('Python' not in programs_list): hwndwrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg') hwndwrapper.ActionLogger().log('\ninstalled_programs:\n') for prog in installed_programs: hwndwrapper.ActionLogger().log(prog) self.assertEqual(('Microsoft' in programs_list) or ('Python' in programs_list), True) finally: window.Close(2.0)
def _unittests(): "Do a quick test of finding some windows" windows = find_elements(class_name_re="#32770", enabled_only=False, visible_only=False) for win in windows: print("==" * 20) print(win.dump_window())
def _unittests(): "Do a quick test of finding some windows" windows = find_elements( class_name_re = "#32770", enabled_only = False, visible_only = False) for win in windows: print("==" * 20) print(win.dump_window())
def test_connect_windowspec(self): """Test that connect_() works with a windowspec""" app1 = Application() app1.start(_notepad_exe()) #unused var: handle = app1.UntitledNotepad.handle app_conn = Application() try: app_conn.connect(title = "Untitled - Notepad") except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only = True, title = "Untitled - Notepad") app_conn.connect(handle = wins[0].handle) except findwindows.ElementNotFoundError: WaitUntil(30, 0.5, lambda: len(findwindows.find_elements(active_only = True, title = "Untitled - Notepad")) > 0) wins = findwindows.find_elements(active_only = True, title = "Untitled - Notepad") app_conn.connect(handle = wins[0].handle) self.assertEqual(app1.process, app_conn.process) app_conn.UntitledNotepad.MenuSelect('File->Exit')
def close_window_titlenm(titlenm='CPSYSDIB'): procs = findwindows.find_elements() for proc in procs: if proc.name == titlenm: app = Application(backend="uia").connect( process=proc.process_id) # process 연결 dig = app[proc.name] #print(dig.print_control_identifiers()) #dig.Edit.type_keys('pywinauto{ENTER}test') klick = dig['확인Button'].click() return klick
def test_wait_cpu_usage_lower(self): """Test that wait_cpu_usage_lower() works correctly""" if is_x64_Python() != is_x64_OS(): return None app = Application().Start(r'explorer.exe') def _cabinetwclass_exist(): "Verify if at least one active 'CabinetWClass' window is created" l = findwindows.find_elements(active_only = True, class_name = 'CabinetWClass') return (len(l) > 0) WaitUntil(40, 0.5, _cabinetwclass_exist) handle = findwindows.find_elements(active_only = True, class_name = 'CabinetWClass')[-1].handle window = WindowSpecification({'handle': handle, 'backend': 'native', }) explorer = Application().Connect(process = window.process_id()) try: explorer.WaitCPUUsageLower(threshold = 1.5, timeout = 60, usage_interval = 2) window.AddressBandRoot.ClickInput() window.TypeKeys(r'Control Panel\Programs\Programs and Features', with_spaces=True, set_foreground=True) window.TypeKeys(r'{ENTER}', set_foreground = False) WaitUntil(40, 0.5, lambda: len(findwindows.find_elements(active_only = True, title = 'Programs and Features', class_name='CabinetWClass')) > 0) explorer.WaitCPUUsageLower(threshold = 1.5, timeout = 60, usage_interval = 2) installed_programs = window.FolderView.texts()[1:] programs_list = ','.join(installed_programs) if ('Microsoft' not in programs_list) and ('Python' not in programs_list): HwndWrapper.ImageGrab.grab().save(r'explorer_screenshot.jpg') HwndWrapper.ActionLogger().log('\ninstalled_programs:\n') for prog in installed_programs: HwndWrapper.ActionLogger().log(prog) self.assertEqual(('Microsoft' in programs_list) or ('Python' in programs_list), True) finally: window.Close(2.0)
def find_element(entry_list=None, visible_only=True, enabled_only=True, active_only=True): """ It takes an entry list and returns the unique element that matches the entry list :param entry_list: full path list :param visible_only: If True, only visible elements are returned, defaults to True (optional) :param enabled_only: If True, only enabled controls are returned, defaults to True (optional) :param active_only: If True, only active windows are considered, defaults to True (optional) :return: The element and the list of candidates """ window_candidates = find_window_candidates(entry_list[0], visible_only=visible_only, enabled_only=enabled_only, active_only=active_only) if window_candidates is None: return None, [] window_candidates = filter_window_candidates(window_candidates) if len(entry_list) == 1 and len(window_candidates) == 1: return window_candidates[0], [] candidates = [] for window in window_candidates: title, control_type, _, _ = get_entry(entry_list[-1]) if is_regex_entry(entry_list[-1]): eis = findwindows.find_elements(title_re=title, control_type=control_type, backend="uia", parent=window, top_level_only=False) descendants = [UIAWrapper(ei) for ei in eis] candidates += filter(lambda e: match_entry_list(get_entry_list(get_wrapper_path(e)), entry_list), descendants) else: descendants = window.descendants(title=title, control_type=control_type) # , depth=max(1, len(entry_list)-2) candidates += filter(lambda e: match_entry_list(get_entry_list(get_wrapper_path(e)), entry_list), descendants) if not candidates: if active_only: return find_element(entry_list, visible_only=True, enabled_only=False, active_only=False) else: return None, [] elif len(candidates) == 1: return candidates[0], [] else: return None, candidates
def test_find_elements_re(self): """Test for bug #90: A crash in 'find_elements' when called with 'title_re' argument""" self.dlgspec.Wait('visible') windows = findwindows.find_elements(title_re="Untitled - Notepad") self.assertTrue(len(windows) >= 1)
def _cabinetwclass_exist(): "Verify if at least one active 'CabinetWClass' window is created" l = findwindows.find_elements(active_only=True, class_name='CabinetWClass') return (len(l) > 0)
import time from pywinauto import Application, findwindows, Desktop from pywinauto.timings import wait_until from appium import webdriver desktop = Desktop(backend="uia") nordlocker_app = Application() nordlocker_app.start('C:\\Program Files\\NordLocker\\NordLauncher.exe', timeout=10) connected_nordlocker = Application(backend="uia") try: connected_nordlocker.connect(title='NordLocker') except findwindows.WindowAmbiguousError: wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) except findwindows.ElementNotFoundError: wait_until( 30, 0.5, lambda: len( findwindows.find_elements(active_only=True, title="NordLocker")) > 0) wins = findwindows.find_elements(active_only=True, title="NordLocker") connected_nordlocker.connect(handle=wins[0].handle) main_screen = connected_nordlocker.window(title='NordLocker') def timeoutError(): main_screen = connected_nordlocker.window(title='NordLocker') try:
def generate(self): if 1 < len( findwindows.find_elements( title= "SFinGe - Synthetic Fingerprint Generator - Demo Version") ): self.familicide() app = Application(backend='uia').start('SFinGeDemo/SFinGe.exe') self.location = "App started" main = app.Dialog #Open generation form self.location = "Main opened" main.Generate.wait('enabled').click() self.location = "Size dialog opened" main.Dialog.OK.wait('enabled').click() form = main.Dialog #Step 1 - Fingerprint mask generation self.location = "Step 1 - Fingerprint mask generation" self.select_combobox_top(form.child_window(auto_id='1024', control_type='ComboBox'), number_of_items=5) #always select thumb self.location = "Step 1 - Finger selected" form.Generate.click() #generate random mask self.location = "Step 1 - Random mask generated" #form.type_keys('%n') form.Next.click() #Step 2 - Directional map generation self.location = "Step 2 - Directional map generation" self.randomize_fingerprint_class( form.child_window(title='Fingerprint class', control_type='ComboBox')) self.location = "Step 2 - Fingerprint class selected" self.randomize_slider( form.child_window(title='Direction perturbation', control_type='Slider')) self.location = "Step 2 - Direction perturbation selected" form.Generate.click() #generate random directional map self.location = "Step 2 - Random directional map generated" #form.type_keys('%n') form.Next.click() #Step 3 - Density map and ridge pattern generation self.location = "Step 3 - Density map and ridge pattern generation" self.randomize_slider( form.child_window(title='Seeds', control_type='Slider')) self.location = "Step 3 - Seeds selected" self.randomize_slider( form.child_window( auto_id='1112', #Ridge density control_type='Slider')) self.location = "Step 3 - Ridge density selected" self.randomize_checkbox( form.child_window(title='Add pores', control_type='CheckBox')) self.location = "Step 3 - Pores inclusion set" #form.type_keys('%s') #Start ridge generation #form.type_keys('%n') #form.Next.click() form.Button5.click() self.location = "Step 3 - Ridge generation started" form.Next.click() #Step 4 - Permanent scratches self.location = "Step 4 - Permanent scratches" #rendered automatically, so nothing we need to to here #form.type_keys('%n') form.Next.click() #Step 5 - Finger contact region self.location = "Step 5 - Finger contact region" self.randomize_slider( form.child_window( title='Displacement', auto_id='1171', #vertical displacement control_type='Slider'), min_perc=40, max_perc=60) self.location = "Step 5 - Vertical displacement selected" self.randomize_slider( form.child_window( auto_id='1170', #horizontal displacement control_type='Slider'), min_perc=40, max_perc=60) self.location = "Step 5 - Horizontal displacement selected" #form.type_keys('%a') form.Apply.click() self.location = "Step 5 - Contact region applied" #form.type_keys('%n') form.Next.click() #Step 6 - Pressure/Dryness self.location = "Step 6 - Pressure/Dryness" self.randomize_slider( form.child_window( auto_id='1104', #pressure/dryness control_type='Slider'), min_perc=16, max_perc=84) self.location = "Step 6 - Pressure/dryness selected" #form.type_keys('%a') form.Apply.click() self.location = "Step 6 - Pressure/dryness applied" #form.type_keys('%n') form.Next.click() #Step 7 - Fingerprint distortion self.location = "Step 7 - Fingerprint distortion" self.randomize_slider( form.child_window(title='Rotation', control_type='Slider')) self.location = "Step 7 - Rotation selected" self.randomize_slider( form.child_window( title='Translation', auto_id='1171', #vertical translation control_type='Slider')) self.location = "Step 7 - Vertical translation selected" self.randomize_slider( form.child_window( auto_id='1170', #horizontal translation control_type='Slider')) self.location = "Step 7 - Horizontal translation selected" self.randomize_slider( form.child_window(title='Skin Elasticity', control_type='Slider')) self.location = "Step 7 - Skin elasticity selected" #form.type_keys('%a') form.Apply.click() self.location = "Step 7 - Distortion applied" #form.type_keys('%n') form.Next.click() #Step 8 - Noising and rendering self.location = "Step 8 - Noising and rendering" self.randomize_slider( form.child_window( title='Ridges', #ridge noise control_type='Slider'), max_perc=50) self.location = "Step 8 - Ridge noise selected" self.randomize_slider( form.child_window( title='Prominence', #ridge prominence control_type='Slider')) self.location = "Step 8 - Ridge prominence selected" self.randomize_slider( form.child_window( title='Valleys', #valley noise control_type='Slider')) self.location = "Step 8 - Valley noise selected" self.randomize_slider( form.child_window(title='Scratches', control_type='Slider')) self.location = "Step 8 - Scratches selected" #form.type_keys('%n') form.Next.click() #Step 9 - Fingerprint rotation and translation self.location = "Step 9 - Fingerprint rotation and translation" #form.type_keys('%a') form.Apply.click() self.location = "Step 9 - Rotation and translation applied" #form.type_keys('%n') form.Next.click() #Step 10 - Background and contrast self.location = "Step 10 - Background and contrast" self.select_combobox_top(form.child_window(title='Background', control_type='ComboBox'), number_of_items=11) self.location = "Step 10 - Background set to no background" self.randomize_slider(form.child_window(title='Gamma', control_type='Slider'), max_perc=40) self.location = "Step 10 - Gamma selected" #form.Generate.click() #form.type_keys('{ENTER}') form.Finish.click() #Save image to file self.location = "Back in main" global directory, filename, file_path main['Save image to file'].click() save_dialog = main.Dialog self.location = "Save dialog" #save_dialog.type_keys(directory) save_dialog.child_window(title='File name:', control_type='Edit')\ .wait('visible').set_edit_text(directory) self.location = "Directory string entered" #save_dialog.type_keys('%s') save_dialog.Save.click() self.location = "Directory changed" time.sleep(1) already_existed = os.path.exists(file_path) #save_dialog.type_keys(filename) save_dialog.child_window(title='File name:', control_type='Edit')\ .wait('visible').set_edit_text(filename) self.location = "Filename string entered" #save_dialog.type_keys('%s') save_dialog.Save.click() self.location = "Save clicked" if already_existed: #save_dialog.Dialog.type_keys('%y') #yes save_dialog.Dialog.Yes.wait('visible').click() self.location = "File overwritten" time.sleep(1) #Close application self.location = "Back in main again" main.Exit.click()
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)
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
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" """ app = Application() starter = app.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) WaitUntil(_ready_timeout, _retry_interval, _cabinetwclass_exist) handle = findwindows.find_elements(active_only = True, class_name = class_name)[-1].handle window = WindowSpecification({'handle': handle, 'backend': 'native', }) explorer = Application().Connect(process=window.process_id()) cur_state = None try: # Go to "Control Panel -> Notification Area Icons" window.Wait("ready", timeout=_ready_timeout) window.AddressBandRoot.click_input() window.type_keys( r'control /name Microsoft.NotificationAreaIcons', with_spaces=True, set_foreground=True) # 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.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout) # Get the new opened applet notif_area = explorer.Window_(title="Notification Area Icons", class_name=class_name) notif_area.Wait("ready", timeout=_ready_timeout) cur_state = notif_area.CheckBox.GetCheckState() # 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.WaitCPUUsageLower(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
def test_find_elements_re(self): """Test for bug #90: A crash in 'find_elements' when called with 'title_re' argument""" self.dlgspec.Wait('visible') windows = findwindows.find_elements(title_re = "Untitled - Notepad") self.assertTrue(len(windows) >= 1)
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" """ app = Application() starter = app.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) WaitUntil(_ready_timeout, _retry_interval, _cabinetwclass_exist) handle = findwindows.find_elements(active_only=True, class_name=class_name)[-1].handle window = WindowSpecification({ 'handle': handle, 'backend': 'native', }) explorer = Application().Connect(process=window.process_id()) cur_state = None try: # Go to "Control Panel -> Notification Area Icons" window.Wait("ready", timeout=_ready_timeout) window.AddressBandRoot.click_input() window.type_keys(r'control /name Microsoft.NotificationAreaIcons', with_spaces=True, set_foreground=True) # 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.WaitCPUUsageLower(threshold=5, timeout=_ready_timeout) # Get the new opened applet notif_area = explorer.Window_(title="Notification Area Icons", class_name=class_name) notif_area.Wait("ready", timeout=_ready_timeout) cur_state = notif_area.CheckBox.GetCheckState() # 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.WaitCPUUsageLower(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