def r_click_paste(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for element in w.descendants(): if element.window_text() == "Shell Folder View": element = element src_x = element.rectangle().mid_point().x src_y = element.rectangle().mid_point().y pywinauto.mouse.click(button='right', coords=(src_x, src_y)) time.sleep(0.5) top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == "Context": w = w for item in w.descendants(): if item.window_text() == "Paste": src_x = item.rectangle().mid_point().x src_y = item.rectangle().mid_point().y pywinauto.mouse.click(coords=(src_x, src_y)) print("Right click c-p done") time.sleep(1) break
def open_app(app_name, app_path): import win32gui import pywinauto import win32con import subprocess import os def open(): file = app_path.split("\\")[-1] dir = app_path.split("\\")[0:-1] dir = "\\".join(dir) os.system(f"cd {dir}") os.system(f"start {file}") print(f"Opened {app_name}") def switch(hwnd): win32gui.SetForegroundWindow(hwnd) win32gui.ShowWindow(w.handle, win32con.SW_MAXIMIZE) print(f"Switched to {app_name}") return windows = pywinauto.Desktop(backend="uia").windows() # check if the app is on the foreground if app_name in win32gui.GetWindowText(win32gui.GetForegroundWindow()): print("do nothing") return #check if the app is opened for w in windows: if app_name in w.window_text(): #bring it to foreground switch(w.handle) return open()
def get_win32_selector_completions(needle): if needle.startswith("template"): filename = f"{int(time.time())}.bmp" region = ImageRegionTool( filename=os.path.join(os.getcwd(), filename)).run() if region is None: return [] return [f"template=${{EXECDIR}}{os.path.sep * 2}{filename}"] elif needle.startswith("uia"): point = PointPickTool().run() if point is None: return [] element = pywinauto.Desktop(backend="uia").from_point(*point) results = [] for attribute in ( "name", "rich_text", "automation_id", "control_type", "class_name", ): value = getattr(element, attribute, None) if callable(value): value = value() if value: results.append(f"{attribute}:{value}") return results else: return []
def get_chrome_alert(): global windows if windows != pywinauto.Desktop(backend="uia").windows( class_name_re='.*Chrome.*', title_re='.*Chrome.*'): windows = pywinauto.Desktop(backend="uia").windows( class_name_re='.*Chrome.*', title_re='.*Chrome.*') + windows for window in windows: alert = None chrome = window for child in window.children(): if 'Compartilhar sua tela' in child.get_properties()['texts']: alert = child return (chrome, alert)
def upload_files(file_path, file, *args): url = "https://www.layui.com/demo/upload.html" chrome_driver = r"D:\chromedriver.exe" browser = webdriver.Chrome(executable_path=chrome_driver) browser.get(url=url) # 点击图片上传按钮,打开文件选择窗口 browser.find_element_by_css_selector(".layui-btn#test2").click() # 使用pywinauto来选择文件 app = pywinauto.Desktop() # 选中文件上传的窗口 打开 dlg = app["打开"] dlg.print_control_identifiers() # 选中文件地址输入工具框 dlg["Toolbar3"].click() send_keys(file_path) send_keys("{VK_RETURN}") # 选中文件名输入框 # 输入第一个文件名 dlg["Edit"].type_keys('"{}"'.format(file)) # 遍历不定长参数文件名 for i in args: send_keys('"{}"'.format(i)) # 输入第二个文件名采取键盘操作 dlg["打开(&O)"].click()
def add_windows(self): dsk = pywinauto.Desktop(backend='uia') explorer = pywinauto.Application().connect(path='explorer.exe') self.windows_list.append(explorer.win1) self.windows_list.append(explorer.win2) self.windows_list.append(explorer.win3) self.windows_list.append(explorer.win4)
def open_app(app_name, app_path): import win32gui import pywinauto import win32con import subprocess def open(): file = app_path.split("\\")[-1] print(file) dir = app_path.split("\\")[0:-1] dir = "\\".join(dir) print(dir) os.chdir(dir) os.startfile(file) print(f"Opened {app_name}") def switch(hwnd): win32gui.SetForegroundWindow(hwnd) win32gui.ShowWindow(w.handle, win32con.SW_MAXIMIZE) print(f"Switched to {app_name}") return windows = pywinauto.Desktop(backend="uia").windows() #check if the app is opened for w in windows: print(w) if app_name in w.window_text(): #bring it to foreground switch(w.handle) return #open the app if it hasn't been opened open() return
def kill_window_activate_notice(): windows = pywinauto.Desktop(backend="uia").windows() for w in windows: if w.window_text() == "啟用 Windows.移至 [設定] 以啟用 Windows。": win32gui.PostMessage(w.handle, win32con.WM_CLOSE, 0, 0) win32gui.CloseWindow(w.handle) return
def minimize_dialog(self, windowtitle: str) -> None: """Minimize window by its title :param windowtitle: name of the window """ self.logger.info("Minimize dialog: %s", windowtitle) self.dlg = pywinauto.Desktop(backend="uia")[windowtitle] self.dlg.minimize()
def getwindows(): if platform.system() != "Windows" or not usingWinFeatures: return json.dumps({"success": False}), 501, { "ContentType": "application/json" } top_windows = pywinauto.Desktop(backend="uia").windows() returnitem = [window.window_text() for window in top_windows] return "\n".join(returnitem), 200, {"ContentType": "application/text"}
def restore_dialog(self, windowtitle: str) -> None: """Restore window by its title :param windowtitle: name of the window """ self.logger.info("Restore dialog: %s", windowtitle) self.dlg = pywinauto.Desktop(backend="uia")[windowtitle] self.dlg.restore()
def __enable_autologin_using_pywinauto(cls, account_passwords): # https://github.com/pywinauto/pywinauto/issues/472 import sys sys.coinit_flags = 2 import warnings warnings.simplefilter("ignore", UserWarning) import pywinauto desktop = pywinauto.Desktop(allow_magic_lookup=False) account_window = desktop.window( title_re=r'계좌비밀번호 입력 \(버전: [0-9]+.+[0-9]+\)') try: cls.logger.info('Waiting for account window to show up') timeout_account_window_ready = 5 account_window.wait('ready', timeout_account_window_ready) except pywinauto.timings.TimeoutError: cls.logger.info('Cannot find account window') raise else: cls.logger.info('Account window found') if cls.__is_in_development: account_window.logging.info_control_identifiers() cls.logger.info('Enabling auto login') account_window['CheckBox'].check() account_combo = account_window['ComboBox'] account_cnt = account_combo.item_count() cls.logger.info('Putting account passwords') for i in range(account_cnt): account_combo.select(i) account_no = account_combo.selected_text().split()[0] if account_no in account_passwords: account_window['Edit'].set_text( account_passwords[account_no]) elif '0000000000' in account_passwords: account_window['Edit'].set_text( account_passwords['0000000000']) account_window['등록'].click() cls.logger.info('Closing account window') account_window['닫기'].click() try: cls.logger.info('Wating account window to be closed') timeout_account_window_done = 5 account_window.wait_not('visible', timeout_account_window_done) except pywinauto.timings.TimeoutError: cls.logger.info('Cannot sure account window is closed') raise else: cls.logger.info('Account window closed')
def enable_autologin_with_control(control): logging.info('start enabling autologin') executor = futures.ThreadPoolExecutor() logging.info('showing account window') _future = executor.submit(control.ShowAccountWindow) desktop = pywinauto.Desktop(allow_magic_lookup=False) account_window = desktop.window(title_re=r'계좌비밀번호 입력 \(버전: [0-9].+[0-9]+\)') try: logging.info('waiting for account window to show up') timeout_account_window_ready = 5 account_window.wait('ready', timeout_account_window_ready) except pywinauto.timings.TimeoutError: logging.info('cannot find account window') raise else: logging.info('account window found') if is_in_development: account_window.logging.info_control_identifiers() logging.info('enabling auto login') account_window['AUTO'].check() account_passwords = config.get('koapy.backend.kiwoom.login.account_passwords') account_combo = account_window['ComboBox'] account_cnt = account_combo.item_count() logging.info('putting account passwords') for i in range(account_cnt): account_combo.select(i) account_no = account_combo.selected_text().split()[0] if account_no in account_passwords: account_window['Edit'].set_text(account_passwords[account_no]) elif '0000000000' in account_passwords: account_window['Edit'].set_text(account_passwords['0000000000']) account_window['등록'].click() logging.info('closing account window') account_window['닫기'].click() try: logging.info('wating account window to be closed') timeout_account_window_done = 5 account_window.wait_not('visible', timeout_account_window_done) except pywinauto.timings.TimeoutError: logging.info('cannot sure account window is closed') raise else: logging.info('account window closed') executor.shutdown()
def __init__(self, path_separator='->', type_separator='||'): Thread.__init__(self) core.path_separator = path_separator core.type_separator = type_separator self.main_overlay = oaam.Overlay(transparency=0.5) self.desktop = pywinauto.Desktop(backend='uia', allow_magic_lookup=False) self._is_running = False self.daemon = True self.event_list = [] self.last_element_event = None self.start()
def opened_windows(*a, **kw): """ Generator that yields Window tuples for all visible windows All arguments are passed to pywinauto.findwindows.find_windows() """ desktop = pywinauto.Desktop() for handle in pywinauto.findwindows.find_windows(*a, **kw): spec = desktop.window(handle=handle) title = spec.window_text() pid = spec.process_id() yield Window(spec, title, handle, pid)
def upload_file(file_path, filename): # 调用外部库,实现上传文件操作,file_path:需要上传的文件路径, filename:上传的文件名称 app = pywinauto.Desktop() # 使用pywinauto来选择文件 dlg = app["打开"] # 选择文件上传的窗口 dlg["Toolbar3"].click() # 选择文件地址输入框 time.sleep(2) send_keys(file_path) send_keys("{VK_RETURN}") # 键盘输入回车,打开该路径 time.sleep(1) dlg["文件名(&N):Edit"].type_keys(filename) # 选中文件名输入框,输入文件名 time.sleep(2) dlg["打开(&O)"].click() # 点击打开 time.sleep(1)
def close(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for element in w.descendants(): if element.automation_id() == "Close": close_x = element.rectangle().mid_point().x close_y = element.rectangle().mid_point().y pywinauto.mouse.click(coords=(close_x, close_y)) break else: pass
def select_file_in(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for item in w.descendants(): if "keyb_c_f_pc_" in item.window_text(): src_x = item.rectangle().mid_point().x src_y = item.rectangle().mid_point().y pywinauto.mouse.click(coords=(src_x, src_y)) break else: pass
def enable_autologin_using_pywinauto(cls, account_passwords): import pywinauto is_in_development = False desktop = pywinauto.Desktop(allow_magic_lookup=False) account_window = desktop.window( title_re=r"계좌비밀번호 입력 \(버전: [0-9]+.+[0-9]+\)") try: cls.logger.info("Waiting for account window to show up") timeout_account_window_ready = 15 account_window.wait("ready", timeout_account_window_ready) except pywinauto.timings.TimeoutError: cls.logger.info("Cannot find account window") raise else: cls.logger.info("Account window found") if is_in_development: account_window.logging.info_control_identifiers() cls.logger.info("Enabling auto login") account_window["CheckBox"].check() account_combo = account_window["ComboBox"] account_cnt = account_combo.item_count() cls.logger.info("Putting account passwords") for i in range(account_cnt): account_combo.select(i) account_no = account_combo.selected_text().split()[0] if account_no in account_passwords: account_window["Edit"].set_text( account_passwords[account_no]) elif "0000000000" in account_passwords: account_window["Edit"].set_text( account_passwords["0000000000"]) account_window["등록"].click() cls.logger.info("Closing account window") account_window["닫기"].click() try: cls.logger.info("Wating account window to be closed") timeout_account_window_done = 5 account_window.wait_not("visible", timeout_account_window_done) except pywinauto.timings.TimeoutError: cls.logger.info("Cannot sure account window is closed") raise else: cls.logger.info("Account window closed")
def get_chrome_alert(): global windows if windows == []: windows = pywinauto.Desktop(backend="uia").windows(class_name_re='.*Chrome.*', title_re='.*Chrome.*') for window in windows: alert = None chrome = window for child in window.children(): if 'Essa página diz' in child.get_properties()['texts']: alert = child return (chrome, alert)
def find(self, element_path): if not self.click_desktop: self.click_desktop = pywinauto.Desktop(backend='uia', allow_magic_lookup=False) if Region.common_path: element_path2 = Region.common_path + core.path_separator + element_path else: element_path2 = element_path entry_list = core.get_entry_list(element_path2) i = 0 unique_element = None elements = None strategy = None while i < 99: while unique_element is None and not elements: try: unique_element, elements = core.find_element( self.click_desktop, entry_list, window_candidates=[], regex_title=self.regex_title) if unique_element is None and not elements: time.sleep(2.0) except Exception: pass i += 1 _, _, y_x, _ = core.get_entry(entry_list[-1]) if y_x is not None: nb_y, nb_x, candidates = core.get_sorted_region(elements) if core.is_int(y_x[0]): unique_element = candidates[int(y_x[0])][int(y_x[1])] else: ref_entry_list = core.get_entry_list(Region.common_path) + core.get_entry_list(y_x[0]) ref_unique_element, _ = core.find_element( self.click_desktop, ref_entry_list, window_candidates=[], regex_title=self.regex_title) ref_r = ref_unique_element.rectangle() r_y = 0 while r_y < nb_y: y_candidate = candidates[r_y][0].rectangle().mid_point()[1] if ref_r.top < y_candidate < ref_r.bottom: unique_element = candidates[r_y][y_x[1]] break r_y = r_y + 1 else: unique_element = None if unique_element is not None: #Region.wait_element_is_ready(unique_element) wait_is_ready_try1(unique_element) break time.sleep(0.1) if not unique_element: raise Exception("Unique element not found! ", element_path2) return unique_element
def keyboard_paste(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for element in w.descendants(): if element.window_text() == "Shell Folder View": element = element src_x = element.rectangle().mid_point().x src_y = element.rectangle().mid_point().y pywinauto.mouse.click(coords=(src_x, src_y)) pywinauto.keyboard.send_keys('^v') print("Keybord c-p done") time.sleep(0.5) break
def r_click_copy(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for item in w.descendants(): if "keyb_c_f_pc_" in item.window_text(): src_x = item.rectangle().mid_point().x src_y = item.rectangle().mid_point().y pywinauto.mouse.click(button='right', coords=(src_x, src_y)) time.sleep(0.5) top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == "Context": w = w for item in w.descendants(): if item.window_text() == "Copy": src_x = item.rectangle().mid_point().x src_y = item.rectangle().mid_point().y pywinauto.mouse.click(coords=(src_x, src_y)) time.sleep(1) break
def keyboard_copy(folder_name): top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for item in w.descendants(): # print(item.window_text()) if "keyb_c_f_pc_" in item.window_text(): src_x = item.rectangle().mid_point().x src_y = item.rectangle().mid_point().y pywinauto.mouse.click(coords=(src_x, src_y)) pywinauto.keyboard.send_keys('^c') time.sleep(0.5) break else: pass
def prepare_to_move_window(folder_name): time.sleep(1) top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w # print("folder_name", w) for element in w.descendants(): # print("descendants", element) if element.automation_id() == "TitleBar": src_x = element.rectangle().mid_point().x src_y = element.rectangle().mid_point().y pywinauto.mouse.press(coords=(src_x, src_y)) break else: pass
def upload_file(file_path, file, doc='', *args): try: # 选择文件 app = pywinauto.Desktop() dlg = app["打开"] dlg["Toolbar3"].click() send_keys(file_path) send_keys("{VK_RETURN}") dlg["文件名(&N):Edit"].type_keys('"{}"'.format(file)) for i in args: send_keys('"{}"'.format(i)) dlg["打开(&O)"].click() log.info(doc + "上传文件成功") except Exception as e: log.error(doc + "上传文件失败") raise e
def drop(folder_name): time.sleep(0.5) top_windows = pywinauto.Desktop(backend="uia").windows() for w in top_windows: if w.window_text() == folder_name: w = w for element in w.descendants(): if element.window_text() == "Shell Folder View": element = element src_x = element.rectangle().mid_point().x src_y = element.rectangle().mid_point().y pywinauto.mouse.move(coords=(src_x, src_y)) time.sleep(0.1) pywinauto.mouse.release(coords=(src_x, src_y)) print("Dnd done") time.sleep(1) break
def __init__(self): Thread.__init__(self) self.main_overlay = oaam.Overlay(transparency=0.5) self.info_overlay = oaam.Overlay(transparency=0.0) self.desktop = pywinauto.Desktop(backend='uia', allow_magic_lookup=False) self.daemon = True self.event_list = [] self.mode = 'Pause' self.last_element_event = None self.distance_inside = 0.0 self.mouse_x_inside = 99 self.mouse_y_inside = 99 self.hicon = None self.hicon_light_on = None self.hicon_light_off = None self.started_recording_with_keyboard = False self.start()
def analyze(self): executionPath = self.toolInstallPath + self.toolPath Popen(executionPath, shell=True) desktop = pywinauto.Desktop(backend=Automator.backend) dialog = desktop[self.toolName] dialog.wait("visible") controlstring = dialog.print_control_identifiers() print controlstring # Find Maximize button. if exists then click it maximizeButtonExists = controlstring.find("MaximizeButton") if (maximizeButtonExists != -1): maximizeButton = dialog["MaximizeButton"] maximizeButton.click() printinfo("Maximize Button is clicked") else: printinfo("Maximize Button is not clicked")
def get_window_list(self): """Get list of open windows Window dictionaries contain: - title - pid - handle :return: list of window dictionaries """ windows = pywinauto.Desktop(backend="uia").windows() window_list = [] for w in windows: window_list.append({ "title": w.window_text(), "pid": w.process_id(), "handle": w.handle }) return window_list