def print_docs(self): # self.zslr_inputting() while True: if self.zslr_input and not self.print_docs_pressed: gui.sleep(0.25) logger.debug('%s', gw.getActiveWindow().title) if gw.getActiveWindow().title.startswith('In-house processing'): gui.hotkey('shift', 'f9') self.print_docs_pressed = True elif self.print_docs_pressed: # gui.sleep(0.1) gui.sleep(0.25) press_the_button(self.processing, reg=(20, 360, 180, 400), x=37, y=387) gui.press('f8') gui.sleep(0.1) press_the_button(self.zaby_zslr, reg=(5, 152, 30, 220), x=16, y=208) gui.hotkey('shift', 'f2') gui.sleep(0.1) press_the_button(self.green, reg=(300, 190, 400, 225), button='f3') press_the_button(self.processing_marked, reg=(20, 360, 180, 400), x=246, y=300) gui.press('del') gui.sleep(0.1) gui.press('2') gui.sleep(0.1) gui.press('f8') gui.sleep(0.1) press_the_button(self.zslr, reg=(5, 152, 30, 220), button='space') gui.hotkey('shift', 'f2') gui.sleep(0.25) press_the_button(self.mark, reg=(0, 1000, 50, 1060), button='esc') self.zslr_input = False self.print_docs_pressed = False self.print_docs_status = True break
def zlpc_inputting(self): while True: if self.print_docs_status: if gw.getActiveWindow().title.startswith('Messages'): gui.press('f3') elif gw.getActiveWindow().title.startswith('In-house processing'): zlpc_window = gw.getWindowsWithTitle('ZLPC')[0] zlpc_window.activate() elif gw.getActiveWindow().title.startswith('ZLPC'): gui.press('f2') self.print_docs_status = False break elif keyboard.is_pressed('ctrl+='): break
def waitUntil(): mustend = time.time() + 5 while time.time() < mustend: if gw.getActiveWindow().title in "RuneScape": return True time.sleep(1) return False
def getWindow(hWnd=None, title=None): """ Método para obter uma instância de pygetwindow.Window. """ # Caso tenha sido passado um hWnd, será retornado uma instância através dele. if isinstance(hWnd, int): window = pygetwindow.Window(hWnd) # Caso tenha sido passado um título, será retornado uma instância utilizando o título. elif title and isinstance(title, str): # Para que não haja muitos problemas, letras maiúsculas e minúsculas # não farão diferença para obter uma janela. for title_ in pygetwindow.getAllTitles(): if title_.lower() == title.lower(): title = title break window = pygetwindow.getWindowsWithTitle(title)[0] # Caso não tenha sido passado um título, será retornando uma instância da janela ativa. else: window = pygetwindow.getActiveWindow() # Retorna a janela. return window
def get_active_window_im(): aw = gw.getActiveWindow() if not aw or 'Google - Google Chrome' not in aw.title: return NO_RESULT pad = 8 window_region = (aw.left + pad, aw.top + pad, aw.width - pad * 2, aw.height - pad * 2) bbox = (aw.left + pad, aw.top + pad, aw.right - pad, aw.bottom - pad) with mss.mss() as sct: def take_screenshot(): sct_img = sct.grab(bbox) return Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX") def equal(im1, im2): return ImageChops.difference(im1, im2).getbbox() is None im1 = take_screenshot() time.sleep(0.05) im2 = take_screenshot() # prevent mid animation snapshot taking. if not equal(im1, im2): return NO_RESULT return im2, window_region
def visible_windows(self): # print('activated') active_windows = gw.getActiveWindow() # print('Aktiv window: '+ active_windows._hWnd if window_in_list(self.list_visible_windows, active_windows): old_active_window_name = active_windows._hWnd old_active_window = self.list_visible_windows[ old_active_window_name][0] if old_active_window.box != active_windows.box: print('update geometry') self.list_visible_windows[old_active_window_name][ 0] = active_windows for window in self.list_visible_windows: # print('A Window: ' + window._hWnd # print(window) # print('look through the windows') # we use the parameter active window and the dictionary with the window object if window_overlay(active_windows, self.list_visible_windows[window][0]): current_time = datetime.datetime.now() duration = current_time - self.list_visible_windows[window][1] MainCSV().add_time( FilterTab().filter( self.list_visible_windows[window][0].title), duration.seconds) self.list_visible_windows.pop(window) break if not (active_windows._hWnd in self.list_visible_windows): self.list_visible_windows[active_windows._hWnd] = ( active_windows, datetime.datetime.now())
def game_image(): """ Obtains a screenshot of the current game state. :return: image of the game. :raise: if there is no game raise exceptions.GameNotFoundException() """ time.sleep(3) current_window = gw.getActiveWindow() for title in gw.getAllTitles(): if "Colonist: Play" in title: game_window = gw.getWindowsWithTitle(title)[0] game_window.minimize() game_window.maximize() time.sleep(0.4) # Screen capture image = ImageGrab.grab() image = np.array(image) # Removing boarder h, w, *_ = image.shape image = image[10:h - 10, 10: w - 10] image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) game_window.minimize() current_window.maximize() return image else: raise exceptions.GameNotFoundException()
def zslr_inputting(self): self.open_output() while True: if gw.getActiveWindow().title.endswith('x-doc: Output') and self.output_opened and not self.zslr_input: gui.click(x=70, y=275, duration=0) # testing parameters in zslr is here (change to 275) gui.sleep(0.4) gui.write('zslr') gui.press('tab') gui.write('Print output') gui.press('tab', presses=3) gui.write('RU') gui.press('enter', presses=2, interval=0.25) gui.hotkey('ctrl', 's') gui.sleep(0.25) gui.write('BYMSQWHL02') gui.press('tab', presses=2) gui.press('space') gui.press('f3') gui.sleep(0.25) gui.hotkey('ctrl', 's') self.zslr_input = True logger.debug('zslr_inputting final') gui.sleep(1) self.ship_button_pressed = False self.change_button_pressed = False self.message_button_pressed = False self.output_opened = False break
def topOrNot(): windows = gw.getActiveWindow() # print(f"The window's title is \"{windows.title}\" with exactly that many spaces.") if windows is None: window.deiconify() window.lift() window.attributes("-topmost", True) else: if windows.isMaximized: window.lower() window.attributes("-topmost", False) elif not windows.isMaximized and windows.title != '' and windows.title != "Notes window" and windows.title != "Choose a note:" and windows.title != "Save your note:" and windows.title != "tk": window.deiconify() window.attributes("-topmost", False) window.lower() elif not windows.isMaximized and windows.title != '' and windows.title == "Notes window" or windows.title == "Choose a note:" or windows.title == "Save your note:": window.attributes("-topmost", False) elif windows.title == "tk": window.deiconify() window.lift() window.attributes("-topmost", True) else: window.deiconify() window.lift() window.attributes("-topmost", True) window.after(10, topOrNot)
def open_output(self): while True: if not self.ship_button_pressed: gui.sleep(0.5) print(gw.getActiveWindow().title) if gw.getActiveWindow().title.endswith('Display: Overview'): shipment = gui.moveTo(x=58, y=21, duration=0) gui.click(shipment) self.ship_button_pressed = True if self.ship_button_pressed and not self.change_button_pressed: change = gui.moveTo(x=55, y=65, duration=0) gui.click(change) self.change_button_pressed = True if self.change_button_pressed: press_the_button(self.message) self.message_button_pressed = True self.output_opened = True break
def test_basic(): if sys.platform == "win32": subprocess.Popen('notepad') time.sleep(0.5) testWindows = [pygetwindow.getActiveWindow()] # testWindows = pygetwindow.getWindowsWithTitle('Untitled - Notepad') # Not working in other languages assert len(testWindows) == 1 npw = testWindows[0] # testWindows[0] is the selected window basic_win32(npw) elif sys.platform == "linux": subprocess.Popen('gedit') time.sleep(5) testWindows = [pygetwindow.getActiveWindow()] assert len(testWindows) == 1 npw = testWindows[0] # testWindows[0] is the selected window basic_linux(npw) elif sys.platform == "darwin": subprocess.Popen(['touch', 'test.txt']) time.sleep(2) subprocess.Popen(['open', '-a', 'TextEdit', 'test.txt']) time.sleep(5) testWindows = pygetwindow.getWindowsWithTitle('test.txt') assert len(testWindows) == 1 npw = testWindows[0] # testWindows[0] is the selected window basic_macOS(npw) subprocess.Popen(['rm', 'test.txt']) else: raise NotImplementedError( 'PyGetWindow currently does not support this platform. If you have useful knowledge, please contribute! https://github.com/asweigart/pygetwindow' )
def save_screenshot(self, image_exporter_name='pil'): cur_window = gw.getActiveWindow() self.target_window.activate() self.target_window.maximize() time.sleep(2) self.screenshot_dict[image_exporter_name]() cur_window.activate() cur_window.maximize() msg = f'Screenshot Exported Using | {image_exporter_name} | Output File | {self.out_file}' print(msg)
def go_region2(): activeWindow = gw.getActiveWindow() screenSize = screen_information(0) taskbar = taskbar_information() width = screenSize[0] / 2 heigth = screenSize[1] - taskbar activeWindow.restore() activeWindow.moveTo(int(width), 0) activeWindow.resizeTo(int(width), int(heigth))
def get_active_window(self): active_window = gw.getActiveWindow() if active_window is not None: active_window_title = active_window.title #get pid of active window process threadid,active_window_pid = win32process.GetWindowThreadProcessId( gw.getActiveWindow()._hWnd ) # firs check in pids that were already pulled outbefore for temp_pid in self.processes: if temp_pid['pid'] == active_window_pid: return [temp_pid['name'], active_window_title, time.time(), None] # check in active processes if not in stored proccesses self.processes = [] # reset processes for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', ]) self.processes.append(pinfo) if active_window_pid == pinfo['pid'] : return [pinfo['name'], active_window_title, time.time(), None] except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): print('Error while listing processes pid.') return [None, None, time.time(), None]
def moveActiveTo(direction): win = gw.getActiveWindow() toPressurizedWindow(win) if win != None: print(win.area, win.getPressure()) print(win, win.getTouching()) if direction == 'left': win.moveTo(0, win.topleft[1]) elif direction == 'up': win.moveTo(win.topleft[0], 0) elif direction == 'down': win.moveTo(win.topleft[0], getScreenSize()[1] - win.size[1]) elif direction == 'right': win.moveTo(getScreenSize()[0] - win.size[0], win.topleft[1])
def reset(self): print("reset") with xpc.XPlaneConnect() as client: # Verify connection try: # If X-Plane does not respond to the request, a timeout error # will be raised. client.getDREF("sim/test/test_float") except: print("Error establishing connection to X-Plane.") print("Exiting...") return # Setting the starting waypoint set_waypoint(self.waypoints[0]) # Setting simulation speed simulation_dref = "sim/time/sim_speed" client.sendDREF(simulation_dref, 1000.0) res = client.getDREF(simulation_dref) print(res) # Selecting the current and XPlane window current_window = pygetwindow.getActiveWindow() xplane_window = pygetwindow.getWindowsWithTitle("X-System")[0] # Focuss on the Xplane window xplane_window.activate() # Performing the reset command ctr+; on the focussed window keyDown('ctrl') keyDown(';') keyUp('ctrl') keyUp(';') time.sleep(3) # Releasing brakes keyDown('b') keyUp('b') # Return to the old window I was on current_window.activate() # Gives the simulator enough time to reload time.sleep(3) # Get observation obs_incomplete = observation() # time.sleep(3) # Add the waypoint as input aswell current_waypoint = np.array(self.current_waypoint) obs = np.append(obs_incomplete, current_waypoint) print(obs.shape) return obs
def main_function(scriptkey): active_window = gw.getActiveWindow().title title_match_list = ["Intensity", "Ultra", "Monitor", "Scan"] if any(title in active_window for title in title_match_list): start_time = time.time() time.sleep(0.1) keyboard.send("ctrl+c") time.sleep(0.01) print(pyperclip.paste()) das.activate() keyboard.send(scriptkey) keyboard.send("ctrl+v+enter") print("--- %s seconds ---" % (time.time() - start_time)) else: print("I3 not active!")
def init(data): data.binary = None data.box = None data.object_color = data.frame[105:175, 505:575] data.cnt = None data.com = (0, 0) data.prev_window = pgw.getActiveWindow() data.count = 0 data.old_com = (0, 0) data.palmAreaCpy = 0 data.yLimit = 0 data.numFinger = 0
def main_function(dashotkey): active_window = gw.getActiveWindow().title title_match_list = ["Intensity", "Ultra", "lounge", "Monitor", "Scan", "Chat", "CHAT", "%"] if any(title in active_window for title in title_match_list): start_time = time.time() time.sleep(0.1) copy() time.sleep(0.01) print(pyperclip.paste()) das.activate() press_key(dashotkey) paste() press_key(Key.enter) print("--- %s seconds ---" % (time.time() - start_time)) else: print("I3 not active!")
def configure_default_keybinds(): """ Configure the default Spectacle keybinds """ # Horizontal thirds keyboard.add_hotkey("ctrl+win+left", lambda k: h_third(gw.getActiveWindow(), k), args=["left"], suppress=True) keyboard.add_hotkey("ctrl+win+right", lambda k: h_third(gw.getActiveWindow(), k), args=["right"], suppress=True) # Veritcal thirds keyboard.add_hotkey("ctrl+win+up", lambda k: v_third(gw.getActiveWindow(), k), args=["up"], suppress=True) keyboard.add_hotkey("ctrl+win+down", lambda k: v_third(gw.getActiveWindow(), k), args=["down"], suppress=True) # left and right halves (or 2/3rds) keyboard.add_hotkey("alt+win+left", lambda k: half(gw.getActiveWindow(), k), args=["left"], suppress=True) keyboard.add_hotkey("alt+win+right", lambda k: half(gw.getActiveWindow(), k), args=["right"], suppress=True) # Top and bottom halves (or 2/3rds) keyboard.add_hotkey("alt+win+up", lambda k: half(gw.getActiveWindow(), k), args=["up"], suppress=True) keyboard.add_hotkey("alt+win+down", lambda k: half(gw.getActiveWindow(), k), args=["down"], suppress=True) # Center window keyboard.add_hotkey("alt+win+c", lambda: center(gw.getActiveWindow()), suppress=True) # TODO # Multimonitor support (send to next monitor) # keyboard.add_hotkey("ctrl+win+alt+left", lambda k: next_monitor(gw.getActiveWindow()), # args=["left"], suppress=True) # keyboard.add_hotkey("ctrl+win+alt+right", lambda k: next_monitor(gw.getActiveWindow()), # args=["right"], suppress=True)
def focus(self, action): # Obtendo nome da janela track_title = self.section_data[1] # Obtendo informações da janela do vídeo e a janela atualmente em foco active_window = gw.getActiveWindow() try: video_window = gw.getWindowsWithTitle(track_title)[0] except IndexError: raise ClosedSection() # Se a janela em foco não for a do vídeo, espera até que seja if active_window != video_window: while not video_window.isActive: pass # Atualiza o tempo gravado if action == 'update_time()': self.update_time()
def main(): numerator = range(301, 489) denominator = range(501, 999) movesText = clipboard.paste() moveList = findSteps( remover(movesText) ) # send the text files contents to the functions that make it nice and neat keyboard = Controller() # divide up moves from string into array moveList = moveList.strip().split(' ') print(moveList) for index, move in enumerate(moveList): # start doing the steps numerator = range(301, 489) denominator = range(501, 999) try: while gw.getActiveWindow( ).title != "RuneScape": # wiat until we're focused on correct app time.sleep(1) except Exception: # passes for when there isnt a focused window, happens when switching between windows pass time.sleep(random.choice(numerator) / random.choice(denominator) / 13) if move.strip() in "up" and move.strip() != "": keyboard.press(Key.up) # hold down for random amount of time time.sleep( random.choice(numerator) / random.choice(denominator) / 2) keyboard.release(Key.up) if move.strip() in "down" and move.strip() != "": keyboard.press(Key.down) time.sleep( random.choice(numerator) / random.choice(denominator) / 3) keyboard.release(Key.down) if move.strip() in "right" and move.strip() != "": keyboard.press(Key.right) time.sleep( random.choice(numerator) / random.choice(denominator) / 2) keyboard.release(Key.right) if move.strip() in "left" and move.strip() != "": keyboard.press(Key.left) time.sleep( random.choice(numerator) / random.choice(denominator) / 3) keyboard.release(Key.left) time.sleep(random.random() / 35) # time between inputs
def init(data): data.binary = None data.box = None data.object_color = data.frame[105:175, 505:575] data.cnt = None data.com = (0, 0) data.prev_window = pgw.getActiveWindow() data.count = 0 data.action_count = 0 data.old_com = (0, 0) data.palmAreaCpy = 0 data.yLimit = 0 data.numFinger = 0 data.demo_seconds = [10, 15, 20, 25, 30, 35, 40, 45] data.action_list = [5, 8, 4, 7, 6, 2, 9, 1]
def pick_move(board, time_left_on_clock): """ takes in a chess.Board as well as time_left_on_clock in seconds returns a chess.Move """ mouse_was_down = False while True: if win.getActiveWindowTitle() == "Engine Battles": window = win.getActiveWindow() if window is not None: fs = (window.height - 39) // 8 mx, my = mouse.get_position() wx, wy = window.left, window.top x = mx - wx - 8 y = my - wy - 31 file = x // fs rank = y // fs if mouse.is_pressed(): if not mouse_was_down: if 0 <= rank < 8 and 0 <= file < 8: start = f"{'abcdefgh'[file]}{8-rank}" # print("down:", start) mouse_was_down = True else: if mouse_was_down: if 0 <= rank < 8 and 0 <= file < 8: end = f"{'abcdefgh'[file]}{8-rank}" # print("up:", end) if start != end: move = chess.Move.from_uci(start + end) if board.is_legal(move): return move mouse_was_down = False
def get_active_window(window): currWindow = gw.getActiveWindow() if currWindow == None or currWindow.title == '': window.category = 'Unclassified' window.title = 'Windows' return elif currWindow._hWnd not in apps: window.title = parse_title(currWindow, window) apps[currWindow._hWnd] = window.title else: window.title = parse_title(currWindow, window) window.title = apps[currWindow._hWnd] if window.title in categories: window.category = categories[window.title] else: window.category = 'Unclassified' return
def print_docs(self): while True: if self.zslr_input and gw.getActiveWindow().title.startswith( 'In-house processing'): gui.hotkey('shift', 'f9') gui.press('tab', presses=8, interval=0.1) gui.press('space') gui.press('f8') gui.press('tab', interval=0.25) gui.press('space') gui.hotkey('shift', 'f2') gui.press('f3') gui.press('tab', presses=7) gui.press('2') gui.press('f8') gui.press('space') gui.hotkey('shift', 'f2') gui.press('f3', presses=2, interval=0.25) break else: gui.sleep(0.25)
def zslr_inputting(self): while True: print('123') if gw.getActiveWindow().title.endswith( 'x-doc: Output' ) and self.output_opened and not self.zslr_input: zslr = gui.moveTo(x=70, y=234, duration=0) gui.click(zslr) gui.write('zslr') gui.write('Print output') gui.press('tab', presses=3) gui.write('RU') gui.press('enter', presses=2, interval=0.25) gui.hotkey('ctrl', 's') gui.write('BYMSQWHL02') gui.press('tab', presses=2) gui.press('space') gui.press('f3', interval=0.25) gui.hotkey('ctrl', 's') self.zslr_input = True print('end') break
# otherwise, grab a reference to the video file else: vs = cv2.VideoCapture(video) height, width = ( int(vs.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(vs.get(cv2.CAP_PROP_FRAME_WIDTH)), ) fps = vs.get(cv2.CAP_PROP_FPS) print(height, width) # initialize the FPS throughput estimator while True: # grab the current frame, then handle if we are using a # VideoStream or VideoCapture object try: title = gw.getActiveWindow().title except: title = '' state, frame = vs.read() # check to see if we have reached the end of the stream frame = cv2.line(frame, (320, 0), (320, 500), (255, 255, 0), 3) if frame is None: break # resize the frame (so we can process it faster) and grab the # frame dimensions image = cv2.flip(frame, 3) (H, W) = frame.shape[:2] if initBB is not None:
db = mic.read() data["noise"] = db """ print("Getting ambient light") cap = cv2.VideoCapture(0) assert cap.isOpened() ret, frame = cap.read(0) if ret: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) data["light"] = cv2.mean(gray)[0] cap.release() """ data["light"] = 221 print("Sending Json") try: headers = {'Content-type': 'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) print(json.dumps(data)) except: print("Failed to post") window = gw.getActiveWindow() if not window or not window.title: continue top_window = window.title.lower() # if prev_window != top_window: update_tracker(top_window) # prev_window = top_window time.sleep(0.5)
def is_focused(self): return (gw.getActiveWindow() == self.hwnd)