class Converter: def __init__(self): self.exe = "C://Program Files (x86)/Auntec/嗨格式PDF转换器/HiPdfConvert.exe" self.app = Application(backend="uia") # self.app.start(self.exe) self.app.connect(path=self.exe) # time.sleep(8) def windows(self): s1 = self.app.window(best_match='嗨格式PDF转换器1.0') s2 = s1["pdf转文件"] s2.print_control_identifiers() s3 = s2.child_window(title="文件名称", control_type="Text") s3.type_keys("afda") s4 = s2.child_window(title="开始转换", control_type="Text") s4.type_keys("{ENTER}") def open(self): auto.hotkey("alt", "tab") # auto.moveTo(x=980, y=990) # auto.click() auto.moveTo(x=580, y=251) auto.click() f = "D://mygit/cpa_std/cpa_std/vehicle_insurance/data/pdf/eacd2c918f264f568096f4cea0e698f0.pdf" f = os.path.abspath(f) auto.typewrite(message=f) auto.press("enter") auto.moveTo(x=1400, y=911) auto.click() auto.moveTo(x=700, y=611) auto.click()
def connectToHndlFetchPossibleUrl(self, win_hndl): app = Application(backend='uia') try: app.connect(handle=win_hndl) dlgs = app.windows( ) # for some reason when we fetch the list of opens windows for a given app, urls seems to be fetched 'always' correctly, when we use app.top_window() sometimes url element is empty # when we handle list of windows; then top window is always first on the list; and during checking url validation whe always stop after getting the first url # hacky, but seems to work now except RuntimeError: print('Couldnt connect to last application :(') fetched_url = '' else: potential_urls = self.__findPotentialUrlsFromBrowser(dlgs) fetched_url = self.__findUrlInStringList(potential_urls) # XTODO: Think of a way to fix this brutal way; possibly dlg.wait() could be useful, need to play with it's # parameters, so this wait wouldnt fail # doesnt seem to necessary anymore # if fetched_url == '': # time.sleep(1) # potential_urls = self.__findPotentialUrlsFromBrowser(dlgs) # fetched_url = self.__findUrlInStringList(potential_urls) return fetched_url
def todo(): app = Application(backend='uia') app.connect(title_re=".*Chrome.*") dlg = app.top_window() url = dlg.child_window(title="Address and search bar", control_type="Edit").get_value() site = url.split('/')[0] print(site)
class URL: def giveurl(self): try: self.app = Application(backend='uia') self.app.connect(title_re=".*Chrome.*") self.dlg = self.app.top_window() self.obj = self.dlg.child_window(title="Address and search bar", control_type="Edit") self.url = self.obj.get_value() except Exception: return '' return str(self.url)
def kill_window(): try: for handle in findwindows.find_windows(title_re="(Dropbox Preferences|Preferencias de Dropbox)"): app = Application.connect(Application(), handle=handle) for window in app.windows_(title_re="(Dropbox Preferences|Preferencias de Dropbox)"): logger.warning('Configuration window for Dropbox detected') window.Close() logger.warning('Configuration window for Dropbox closed') except findwindows.WindowNotFoundError: pass
from pywinauto import Application app = Application(backend='uia') app.connect(title_re=".*Chrome.*") ytb = app.Pane.child_window(title_re=".*YouTube.*", control_type="TabItem") def get_song(): song = ytb.window_text() print(song) if "Audio playing" in song: return '-'.join(song.split('-')[:-2]) else: return "Idling" print(get_song())
import threading as th import time import speech_recognition as sr from pywinauto import Application from pywinauto.keyboard import send_keys from os import path import os from PIL import Image from pystray import MenuItem as item import pystray from functools import partial ## Global Flags app = Application(backend='uia') app.connect(title_re=".*Chrome.*", top_level_only=True) dlg = app.top_window() element_name = "Address and search bar" win = tk.Tk() win.title("Bad Word Detector") win.geometry("350x170") running = False Llink = tk.StringVar() LStatus = tk.StringVar() LStatus.set("Inactive") count = 0 ## Items Definitions with open("bad-words.dat", "r") as myfile: ## Load bad words
class RealBandController: """An object for controlling RealBand.""" _TARGET_VERSION = '2018.0.2.5' def __init__(self, binary_path=r'C:\RealBand\RealBand.exe', try_connect=True): self.realband_version = _get_exe_version(binary_path) if self.realband_version != self._TARGET_VERSION: print('This code was written for RealBand {}, your version is {}. ' 'Proceed with caution.' .format(self._TARGET_VERSION, self.realband_version), file=sys.stderr) self._app = Application(backend='win32') if try_connect: try: self._app.connect(path=binary_path) except ProcessNotFoundError: try_connect = False if not try_connect: self._app.start(binary_path) self._app.wait_cpu_usage_lower(threshold=5) def get_ready(): rb_window = self._app.window(class_name='RealBand') if rb_window.exists() and rb_window.is_visible() and rb_window.is_enabled(): return # Reject attempts to recover from a crash dialog = self._app.window(class_name='#32770') dialog_text = dialog.StaticWrapper2.element_info.name if ('Okay to restore all the default settings' in dialog_text or 'Recover data from last session' in dialog_text): dialog.Button2.click() raise TimeoutError() wait_until_passes(func=get_ready, exceptions=(ElementNotFoundError, TimeoutError), timeout=15, retry_interval=1) self._song_pane = self._app.RealBand.children( class_name='TPanelWithCanvas')[10] @property def app(self): return self._app def kill(self): self._app.kill() for proc in psutil.process_iter(): if proc.name() in ['bbw2.exe', 'RealBand.exe']: print('Killing', proc, file=sys.stderr) try: proc.kill() except psutil.NoSuchProcess: traceback.print_exc(file=sys.stderr) def load_song(self, path): """Load a song from the given file.""" self._menu_select('File->Open') self._open_file(path) try: # Get the annoying Comments window out of the way self._app.Comments.minimize() except MatchError: pass def load_style(self, path): """Load a style from the given file.""" self.wait_ready() def open_dialog(): # Bring up the style popup menu and choose to open a style file self._song_pane.click_input(coords=(44, 73), absolute=False) menu = self._app.window(class_name='#32768') menu.menu_item('File Open Style').click_input() wait_until_passes(func=open_dialog, exceptions=ElementNotFoundError, timeout=120, retry_interval=0.4) self._open_file(path) def _open_file(self, path): """Input a path in the file open dialog.""" path = os.path.normpath(os.path.abspath(path)) while True: dialog = self._app.window(class_name='#32770') dialog.wait('ready') # If asked whether to save changes, say no try: dialog_text = dialog.StaticWrapper2.element_info.name if 'Save it?' in dialog_text: dialog.Button2.click() continue except MatchError: pass break dialog.Edit1.set_edit_text(path) dialog.Edit1.send_keystrokes('{ENTER}') self.wait_ready(timeout=60) def save_song(self, path, filetype='MIDI File (.MID) (*.MID)'): """Save the current song under the given filename.""" path = os.path.normpath(os.path.abspath(path)) self._menu_select('File->Save As') file_dialog = self._app.window(class_name='#32770') file_dialog.wait('ready') file_dialog.ComboBox2.select(filetype) file_dialog.Edit1.set_edit_text(path) file_dialog.Edit1.send_keystrokes('{ENTER}') self.wait_ready() def generate_all(self): """Generate all Band-in-a-Box tracks.""" self._menu_select('Generate->Generate All BB Tracks') self.wait_ready() def set_key(self, key, transpose=False): """Set the key of the song.""" if transpose: raise NotImplementedError('transpose not implemented') self._menu_select('Edit->Key Signature') key_dialog = self._app.window(class_name='TKEY') key_dialog.wait('ready') key_dialog.TComboBox1.select(key) key_dialog.TRadioButton4.click() # No Transpose key_dialog.TButton3.click() # OK self.wait_ready() @property def key_signature(self): """The key signature of the song.""" text = self._get_menu_item_text('Edit->Key Signature') return re.search(r'\[([A-G].?)\]$', text).group(1) @property def time_signature(self): """The time signature (meter) of the song.""" text = self._get_menu_item_text('Edit->Meter (Time Signature)') return re.search(r'\[([0-9]+/[0-9]+)\]$', text).group(1) @property def tempo(self): """The tempo of the song.""" text = self._get_menu_item_text('Edit->Tempo') return float(re.search(r'\[([0-9.,]+)\]$', text).group(1)) def _get_menu_item_text(self, path, timeout=10, retry_interval=0.5): def get_text(): return self._app.RealBand.menu_item(path).text() return wait_until_passes(func=get_text, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def _menu_select(self, path, timeout=10, retry_interval=0.5): self.wait_ready() def select_option(): self._app.RealBand.menu_select(path) wait_until_passes(func=select_option, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def wait_ready(self, timeout=30): self._app.RealBand.wait('ready', timeout=timeout)
"""Once a set of identifiers has been created for all controls in the dialog we disambiguate them. use the WindowSpecification.print_control_identifiers() method""" app.YourDialog.print_control_identifiers() """How to Access the System Tray""" import pywinauto.application app = pywinauto.application.Application().connect(path="explorer") systray_icons = app.ShellTrayWnd.NotificationAreaToolbar ClickSystemTrayIcon(button) RightClickSystemTrayIcon(button) """Often, when you click/right click on an icon, you get a popup menu. The thing to remember at this point is that the popup menu is a part of the application being automated not part of explorer.""" # connect to outlook outlook = Application.connect(path='outlook.exe') # click on Outlook's icon taskbar.ClickSystemTrayIcon("Microsoft Outlook") # Select an item in the popup menu outlook.PopupMenu.Menu().get_menu_path("Cancel Server Request")[0].click() app.wait_cpu_usage_lower(threshold=5) # wait until CPU usage is lower than 5% # call ensure_text_changed(ctrl) every 2 sec until it's passed or timeout (4 sec) is expired @always_wait_until_passes(4, 2) def ensure_text_changed(ctrl): if previous_text == ctrl.window_text():
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:
class BandInABoxController: """An object for controlling Band-in-a-Box.""" _TARGET_VERSION = '2018.0.0.520' def __init__(self, binary_path=r'C:\bb\bbw.exe', try_connect=True): self.biab_version = _get_exe_version(binary_path) if self.biab_version != self._TARGET_VERSION: print('This code was written for Band-in-a-Box {}, your version is {}. ' 'Proceed with caution.' .format(self._TARGET_VERSION, self.biab_version), file=sys.stderr) self._app = Application(backend='win32') if try_connect: try: self._app.connect(path=binary_path) except ProcessNotFoundError: try_connect = False if not try_connect: self._app.start(binary_path) self._app.wait_cpu_usage_lower(threshold=5) def get_ready(): rb_window = self._app.window(class_name='TBandWindow') if rb_window.exists() and rb_window.is_visible() and rb_window.is_enabled(): return raise TimeoutError() wait_until_passes(func=get_ready, exceptions=(ElementNotFoundError, TimeoutError), timeout=15, retry_interval=1) @property def app(self): return self._app def kill(self): self._app.kill() for proc in psutil.process_iter(): if proc.name() == 'bbw.exe': print('Killing', proc, file=sys.stderr) try: proc.kill() except psutil.NoSuchProcess: traceback.print_exc(file=sys.stderr) def load_song(self, path): """Load a song from the given file.""" self.menu_select('File->Open') self._open_file(path) def _open_file(self, path): """Input a path in the file open dialog.""" while True: dialog = self._app.window(class_name='#32770') dialog.wait('ready') # If asked whether to save changes, say no try: dialog_text = dialog.StaticWrapper2.element_info.name if 'Save it?' in dialog_text: dialog.Button2.click() continue except MatchError: pass break dialog.Edit1.set_edit_text(path) dialog.Edit1.send_keystrokes('{ENTER}') self._wait_ready(timeout=60) def save_song(self, path): """Save the current song under the given filename.""" self.menu_select('File->Save song As') file_dialog = self._app.window(class_name='#32770') file_dialog.wait('ready') file_dialog.Edit1.set_edit_text(path) file_dialog.Edit1.send_keystrokes('{ENTER}') self._wait_ready() def menu_select(self, path, timeout=10, retry_interval=0.5): self._wait_ready() def select_option(): self._app.TBandWindow.menu_select(path) wait_until_passes(func=select_option, exceptions=(ElementNotEnabled, RuntimeError), timeout=timeout, retry_interval=retry_interval) def _wait_ready(self, timeout=30): self._app.TBandWindow.wait('ready', timeout=timeout)
from pywinauto import Application from pypresence import Presence import time,traceback #Setting up RPC stuff client_id = 'YOUR CLIENT ID' #PASTE UR CLIENT ID HERE RPC = Presence(client_id,pipe=0) RPC.connect() #Getting your chrome stuff app = Application(backend='uia') app.connect(title_re=".*Chrome.*",found_index=0) ytb = app.Pane.child_window(title_re=".*YouTube.*",control_type="TabItem") def get_song(): """getting the video name from the header file""" song = ytb.window_text() #print(song) if "Audio playing" in song: song = '-'.join(song.split('-')[:-2]) if '→' in song: spliting = song.split('→') return spliting[0],'→'.join(spliting[1:]) elif '-' in song: spliting = song.split('-') return spliting[0],'-'.join(spliting[1:]) else: return song,'....' else: