def get_kiosk(self): try: if KIOSK_FIND_BY == 'KIOSK_WINDOW_NAME': h = findwindows.find_window(title = KIOSK_WINDOW_NAME) elif KIOSK_FIND_BY == 'KIOSK_CLASS_NAME': h = findwindows.find_window(class_name_re = KIOSK_CLASS_NAME) Logger.info('Kiosk hwnd: ' + str(h)) Logger.info('Kiosk class: ' + HwndWrapper(h).Class()) Logger.info('Kiosk title: ' + HwndWrapper(h).WindowText()) return h except Exception, err: raise err
def open_zoom(): app = Application().start("Zoom.exe") time.sleep(3) zoom_window = find_window(title="Zoom - 免费账号") MoveWindow(zoom_window, 0, 0, 400, 400) SetForegroundWindow(zoom_window) return zoom_window
def take_screenshot(date_string): SetForegroundWindow(find_window(best_match='NiceHash')) x, y, a, b = pyautogui.locateOnScreen('ir_sample/nicehash_header.png') ImageGrab.grab(bbox=(x - 1, y, x - 1 + NH_WINDOW_W, y + NH_WINDOW_H)).save( "screenshots/{0}.png".format(date_string), "PNG")
def click_kiwoom_pop(): """ 재접속 안내 pop-up창이 뜨면, 확인 버튼을 눌러 준다. :return: """ found = False listtitle = [ "[HTS 재접속 안내]", "안녕하세요. 키움증권 입니다.", "KHOpenAPI", "조회횟수 제한 : -209", "opstarter", "Python" ] for wintitle in listtitle: try: app = application.Application() win = findwin.find_window(title=wintitle) kiwoomapp = app.connect(handle=win) kiwoomspec = kiwoomapp.window(title=wintitle) if wintitle == "Python": kiwoomspec.child_window(title="프로그램 닫기(&C)", class_name="Button").set_focus() kiwoomspec.child_window(title="프로그램 닫기(&C)", class_name="Button").click() else: kiwoomspec.child_window(title="확인").set_focus() kiwoomspec.child_window(title="확인").click() print("%s : Pop-up found : %s" % (time.asctime(), wintitle)) found = True time.sleep(600) except: pass return found
def window_move_thread(): global status while True: time.sleep(1) if status == "playing" or status == "gamePrepairing": continue try: window = find_window(title='XD Showroom') win32gui.ShowWindow(window, win32con.SW_RESTORE) win32gui.SetWindowPos(window, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos(window, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos( window, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) pos = 333 win32api.SetCursorPos((pos, pos)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, pos, pos, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, pos, pos, 0, 0) except: pass
def findTitle(ai, pattern): ai.findPID() pid = 0 WS_BASE = 0x14EF0000 for exe in ai.exe_file: pid = exe['pid'] app = ai.Conn(pid) hwnd = find_window(process=pid) winstl = GetWindowLong(hwnd, GWL_STYLE) if (winstl - WS_BASE) == WS_MINIMIZE: ShowWindow(hwnd, SW_RESTORE) putty = app.PuTTY # #save putty control info stdout = sys.stdout sys.stdout = TextArea() putty.print_control_identifiers() winspec = sys.stdout sys.stdout = stdout for el in winspec.buffer: if el[0].find(pattern) > 0: f1, f2 = el[0].split('=', 1) title = f2.split(',')[0] title = title.replace('"', '') return title return None
def start_miner(active_miner_exe): def check_for_hardware_warning(active_miner_exe): print("searching for hardware warning...") found = pyautogui.locateOnScreen('ir_sample/{0}/dismiss.png'.format( active_miner_exe.dir_name)) if found: x, y, a, b = found pyautogui.click(x + 20, y + 10) def check_for_start_button(active_miner_exe): print("searching for start button...") print('ir_sample/{0}/start.png'.format(active_miner_exe.dir_name)) found = pyautogui.locateOnScreen('ir_sample/{0}/start.png'.format( active_miner_exe.dir_name)) if found: print("found the button") x, y, a, b = found pyautogui.click(x + active_miner_exe.start_offset[0], y + active_miner_exe.start_offset[1]) else: print("did not found the button") print(active_miner_exe.process_name) print("Starting {0}".format(active_miner_exe.process_name)) if not miner_exe_running(active_miner_exe.process_name): subprocess.Popen( active_miner_exe.process_path ) # this will depend on where you have your mining software installed time.sleep( 5) # delay to let miner exe boot, probably overkill, but whatever SetForegroundWindow(find_window(best_match=active_miner_exe.process_name)) if active_mining_exe == "n": check_for_hardware_warning() check_for_start_button(active_miner_exe)
def tap_key(key, delay=1.0): if 操作完后回到原来窗口: original_window = GetForegroundWindow() SetForegroundWindow(find_window(title=FGO窗口名)) k.tap_key(key) time.sleep(0.02) if 操作完后回到原来窗口: SetForegroundWindow(original_window) time.sleep(delay)
def take_screenshot(date_string, active_miner_exe): SetForegroundWindow( find_window(best_match=active_miner_exe.process_name)) x, y, a, b = pyautogui.locateOnScreen( 'ir_sample/{0}/header.png'.format(active_miner_exe.dir_name)) ImageGrab.grab(bbox=(x, y, x - 1 + active_miner_exe.window_width, y + active_miner_exe.window_height)).save( "screenshots/{0}.png".format(date_string), "PNG")
def open_focus(target, p_type='explorer'): try: HwndWrapper(find_window(title=ReportUtilities.base(target))).set_focus() except WindowNotFoundError: Popen('{process} "{path}"'.format( process=p_type, path=target) ) except FileNotFoundError: print('File: {target} does not exist.'.format(target=target))
def test_find_window(self): """Test if function find_window() works as expected including raising the exceptions""" ctrl = self.dlg.OK.wrapper_object() handle = find_window(process=self.app.process, best_match='OK', top_level_only=False) self.assertEqual(handle, ctrl.handle) self.assertRaises(WindowNotFoundError, find_window, process=self.app.process, class_name='OK') self.assertRaises(WindowAmbiguousError, find_window, process=self.app.process, class_name='Button', top_level_only=False)
def lookAtWindow(self, title_re): """ Brings a window that matches title_re to the foreground. Args: title_re: A regular expression that matches the desired window. """ try: SetForegroundWindow(find_window(title_re=title_re)) except WindowNotFoundError as e: print(e)
def TogglePin(self, event): if event.IsChecked(): try: SetForegroundWindow(find_window(title=self.GetTitle())) except: pass self.SetWindowStyleFlag( (wx.CLIP_CHILDREN | wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.BORDER_NONE | wx.FRAME_SHAPED)) else: self.SetWindowStyleFlag((wx.CLIP_CHILDREN | wx.FRAME_NO_TASKBAR | wx.BORDER_NONE | wx.FRAME_SHAPED))
def cut(save_picture=True): hwnd = find_window(title=FGO窗口名) ShowWindow(hwnd, SW_RESTORE) SetForegroundWindow(hwnd) # 截取FGO主窗口截图 left, top, right, bottom = GetWindowRect(hwnd) src_image = ImageGrab.grab((left, top, right, bottom)) src_image = src_image.convert('L').convert('RGB') if save_picture: src_image.save('pic.png') print("截图已完成……") return np.array(src_image)
def open_focus(target, p_type='explorer'): if system() == 'Windows': # pywinauto does not work on OS X from pywinauto.findwindows import find_window, WindowNotFoundError from pywinauto.controls.hwndwrapper import HwndWrapper try: HwndWrapper(find_window(title=ReportUtilities.base(target))).set_focus() except WindowNotFoundError: Popen('{process} "{path}"'.format( process=p_type, path=target) ) except FileNotFoundError: print('File: {target} does not exist.'.format(target=target))
def run_creon_plus(username: str, password: str, certification_password: str, starter_path: str): app = Application().start('%s /prj:cp' % starter_path) sleep(1) typewrite('\n', interval=0.1) dialog = timings.WaitUntilPasses( 30, 1, lambda: app.window(handle=find_window(title='CREON Starter')) ) username_input = getattr(dialog, '1') username_input.Click() username_input.TypeKeys(username) password_input = getattr(dialog, '2') password_input.Click() password_input.TypeKeys(password) certification_password_input = getattr(dialog, '3') certification_password_input.Click() certification_password_input.TypeKeys(certification_password) press('enter')
def main(args = None): if args == None: args = sys.argv[1:] if len(args) < 1: print "Usage: w32toggletitle.py <'part of title'>" sys.exit(0) titlematch = ".*%s.*" % args[0] try: emacsHwnd = findwindows.find_window(title_re=titlematch) except: print "Window not found : %s " % titlematch sys.exit(0) current = win32api.GetWindowLong(emacsHwnd, -16) if current == withTitle: win32api.SetWindowLong(emacsHwnd, -16, woTitle) else: win32api.SetWindowLong(emacsHwnd, -16, withTitle)
def main(args=None): if args == None: args = sys.argv[1:] if len(args) < 1: print "Usage: w32toggletitle.py <'part of title'>" sys.exit(0) titlematch = ".*%s.*" % args[0] try: emacsHwnd = findwindows.find_window(title_re=titlematch) except: print "Window not found : %s " % titlematch sys.exit(0) current = win32api.GetWindowLong(emacsHwnd, -16) if current == withTitle: win32api.SetWindowLong(emacsHwnd, -16, woTitle) else: win32api.SetWindowLong(emacsHwnd, -16, withTitle)
def __init_hwnd(self): """ 初始化窗口操作句柄 :return: """ try: self.__main_window = self.__app.window( title_re=self.main_window_title_re) self.__dialog_hwnd = find_window(top_level_only=False, process=self.__app.process, class_name='AfxMDIFrame42s') self.toolbar = self.__app.window( top_level_only=False, class_name='ToolbarWindow32').wrapper_object() self.tree = self.__app.window( top_level_only=False, class_name='SysTreeView32', parent=self.__dialog_hwnd).wrapper_object() except Exception as e: raise TreadError("000001", "初始化窗口连接句柄出错!{}".format(e))
def run(): zoom_window = open_zoom() activate_movie_window() time.sleep(1) SetForegroundWindow(zoom_window) mouse.click(coords=(150, 150)) # 等待连接 time.sleep(10) # 开始分享 keyboard.SendKeys('%s') # 选择分享哪个程序 time.sleep(1) keyboard.SendKeys('{TAB}') time.sleep(1) keyboard.SendKeys('{TAB}') time.sleep(1) keyboard.SendKeys('{DOWN}') time.sleep(1) keyboard.SendKeys('{RIGHT}') time.sleep(1) # 勾选共享电脑声音 keyboard.SendKeys('{TAB}') time.sleep(1) keyboard.SendKeys('{SPACE}') # 确认分享 time.sleep(1) share_window = find_window(title='选择一个您想共享的窗口或程序') SetForegroundWindow(share_window) time.sleep(1) keyboard.SendKeys('{TAB}') time.sleep(1) keyboard.SendKeys('{TAB}') time.sleep(1) # 定位到了“开始共享”按钮 keyboard.SendKeys('{SPACE}') time.sleep(60 * 30) close_share_window(zoom_window) close_zoom(zoom_window)
def search_window(): """ Find elements based on criteria passed in and return list of their handles :return: """ try: found_window = findwindows.find_window(active_only=True, enabled_only=True, visible_only=True) print('found_window: {}\n'.format(found_window)) return found_window except pywinauto.findwindows.ElementAmbiguousError: print('There was more then one element that matched') except pywinauto.findwindows.ElementNotFoundError: print('No element could be found') except pywinauto.findwindows.WindowAmbiguousError: print('There was more then one window that matched') except pywinauto.findwindows.WindowNotFoundError: print('No window could be found') return []
def insert_command_on_cmdline(wintitle, strcmd, cmdspec=None): """ wintitle을 가진 window을 찾아서 strcmd을 수행시킨다. wintitle은 단지 cmd.exe을 수행한 이후, process가 없는 빈 도스창이다. 만일 cmdspec이 있으면, 이를 사용한다. :param wintitle: :param strcmd: :param cmdspec: if not None, pywinauto windows spec :return: """ strcmd = strcmd + "\n" try: if cmdspec == None: app = application.Application() win = findwin.find_window(title=wintitle) cmdapp = app.connect(handle=win) cmdspec = cmdapp.window(title=wintitle).wrapper_object() cmdspec.send_keystrokes(strcmd) except Exception as e: print(e) pass
def __init__(self, gui): """ :type gui:PyQt5.WindowGUI.WindowGUI """ super().__init__() # gui.setWindowIcon(QIcon(self.resource_path(gui.icon_path))) # gui.icon_area.setPixmap( # QPixmap(self.resource_path(gui.icon_path)).scaled(30, 30)) self.mousePos_pointer = POINT() # マウスカーソル座標の変更用 self.pressedCtrl = False self.pressedShift = False # タイマー処理のインスタンス(別スレッド) self.timerThread = TimerThread() self.timerThread.start() self.timerThread.CtrlTimeoutSignal.connect(self.timeout_Ctrl) self.timerThread.ShiftTimeoutSignal.connect(self.timeout_Shift) # グローバルホットキーに反応 =========================== # 同じキーを押し続けると連続発動するので, # trigger_on release:Trueによって離すまで発動を止める keyboard.add_hotkey('ctrl', lambda: self.onPressCtrl_global(gui), trigger_on_release=True) keyboard.add_hotkey('shift', lambda: self.onPressShift_global(gui), trigger_on_release=True) keyboard.add_hotkey('ctrl+shift,ctrl+shift', lambda: self.autoComplete_single(gui), trigger_on_release=True) keyboard.add_hotkey('ctrl+space', gui.switchMemorize, trigger_on_release=True) keyboard.add_hotkey('shift+tab', gui.rollBack_at_flag, trigger_on_release=True) # このアプリのハンドルを取得 =========================== self.thisHandle = findwindows.find_window(title='Keasy', class_name='Qt5QWindowIcon') self.thisWindowWrapper = hwndwrapper.HwndWrapper(self.thisHandle)
thing_id = 'bob30' helpers.init() def get_rect(hwnd): rect = win32gui.GetWindowRect(hwnd) return rect def screen_grab(): box = (x1, y1, x2, y2) im = ImageGrab.grab(box) return im window = find_window(title="bob_robot_sim") SetForegroundWindow(window) x1, y1, x2, y2 = get_rect(window) class RandomNoise: random_signal_counter = 0 def __init__(self): pass def get_signal(self): if self.random_signal_counter > 0: self.random_signal_counter -= 1
def 等待操作(): print('等待操作') SetForegroundWindow(find_window(title=FGO窗口名)) input()
def find_excel_on_taskbar(title_name='Microsoft Excel - Sheet1'): """find excel and bring to top""" window_id = find_window(title=title_name) set_active_window(window_id)
def close_excel_window(title_name): window_id = find_window(title=title_name) win32gui.PostMessage(window_id, win32con.WM_CLOSE, 0, 0)
from random import sample, uniform from pymongo import MongoClient from start import useful from math import ceil, floor from time import sleep from pywinauto.application import Application from pywinauto.findwindows import find_window wait, collection, app = lambda x, y: sleep(uniform(x, y)), MongoClient( 'mongodb://localhost:27017/').admin, Application().connect( handle=find_window(title_re='Unfriendly')).top_window() app.move_window(x=-10, y=0, width=1365, height=768, repaint=True) # app.minimize() def shortest(heap, target, c=True): m, ret, i, index, decal = 10000, [], 0, [], 0 for x in heap: if x[0][-1]['_id'] == target['_id'] if c else x[0][-1] == target: return None, None, ([x[0]] if c else x[0][1:-1]) if x[1] == m: ret.append(x) index.append(i) elif x[1] < m: m, ret, index = x[1], [x], [i] i += 1 for j in index: del heap[j - decal] decal += 1 return ret, heap, None
def get_player(self): try: return findwindows.find_window(class_name = PLAYER_CLASS_NAME) except Exception, err: raise err
def IsRiotClientOpen(): try: find_window(title='Riot Client') return True except: return False
def IsClientOpen(): try: find_window(title='League of Legends') return True except: return False
def IsLeagueInGame(): try: find_window(title='League of Legends (TM) Client') return True except: return False
def to_front(self): try: hwnd = find_window(title=self.name) SetForegroundWindow(hwnd) except WindowNotFoundError: pass
def nicehash_exe_running(): try: SetForegroundWindow(find_window(best_match='NiceHash')) except MatchError: return False return True
def modifydata(): modi_window = findwindows.find_window(title=r'修改软元件值') print(modi_window)