def _sendRclick(self, hwnd, msg): # IPython magic %paste does not work for remote ssh python # or Windows Subsystem for Linux, so let's send right click using win32 def _pasting(hwnd, msg): sublime.set_clipboard(msg) sleep(0.1) # important! # sending right-click to paste over mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_ABSOLUTE, 0, 0) sleep(0.1) # important! mouse_event(MOUSEEVENTF_RIGHTUP | MOUSEEVENTF_ABSOLUTE, 0, 0) # send enter; int('0x1C0001', 0) works both on WSL and cmd PostMessage(hwnd, WM_KEYDOWN, VK_RETURN, int('0x1C0001', 0)) PostMessage(hwnd, WM_KEYUP, VK_RETURN, int('0xC0000001', 0)) try: # https://stackoverflow.com/a/15503675/566035 shell = Dispatch("WScript.Shell") shell.SendKeys( '%' ) # Sending Alt key goes around windows security policy change SetForegroundWindow(hwnd) except: self.view.show_popup('Invalid handle ({})'.format(hwnd)) return # move mouse to the center of that window oldx, oldy = GetCursorPos() x1, y1, x2, y2 = GetWindowRect(hwnd) x = int((x1 + x2) / 2) y = int((y1 + y2) / 2) SetCursorPos((x, y)) lineN = len(self.view.lines(self.view.sel()[0])) # we need to use %cpaste magic to avoid indentation error # in case more than 2 lines have indentation. if lineN > 2: _pasting(hwnd, r"%cpaste") _pasting(hwnd, msg) _pasting(hwnd, "--") else: _pasting(hwnd, msg) # bring back the mouse cursor SetCursorPos((oldx, oldy)) # bring back the focus to sublime, if subl_handle is known to the plugin if subl_handle: SetForegroundWindow(subl_handle) shell.SendKeys('%') # cancel the Alt key evoked menu
def draw_menu(self, events, overlay): try: SetForegroundWindow(display.get_wm_info()["window"]) except: pass self.menu.update(events) self.menu.draw(overlay)
def __init__(self): self.hwnd = FindWindow(None, "扫雷") # 获取扫雷游戏窗口的句柄 assert self.hwnd, "请先打开扫雷,再运行该脚本程序" SendMessage(self.hwnd, WM_SYSCOMMAND, SC_RESTORE, 0) # 还原最小化 SetForegroundWindow(self.hwnd) # 窗口置顶 self.pixel_size = 16 # 每个格子的大小固定,为16个像素 self.left, self.top, self.right, self.bottom = GetWindowRect( self.hwnd) # 获取窗口坐标 self.rank = None # 扫雷游戏的等级,分为:高级、中级、初级,不包含自定义模式 self.max_mines = 0 # 扫雷游戏的所有雷的数目 # 去除窗口边框,只保留所有格子 self.left = self.left + 15 # 左边框15个像素宽 self.right = self.right - 11 # 右边框11个像素宽 self.bottom = self.bottom - 11 # 下边框11个像素宽 self.top = self.top + 101 # 尚边框101个像素宽 # 获得游戏横向和纵向的格子数目 self.height = int( (self.bottom - self.top) / self.pixel_size) # 扫雷游戏的纵向格子数目 assert self.height in [16, 16, 9] self.length = int( (self.right - self.left) / self.pixel_size) # 扫雷游戏的横向格子数目 assert self.length in [30, 16, 9] # 获取游戏难度级别 self.get_rank() self.get_max_mines()
def _set_foreground(self, grid=None): if grid is None: grid = self._trader.main if grid.has_style(pywinauto.win32defines.WS_MINIMIZE): # if minimized ShowWindow(grid.wrapper_object(), 9) # restore window state else: SetForegroundWindow(grid.wrapper_object()) # bring to front
def get_wind_by_title(self): """显示窗口(此处显示微信)""" from win32gui import FindWindow, SetForegroundWindow, ShowWindow from win32con import SW_RESTORE hwnd = FindWindow("WeChatMainWndForPC", None) # text = GetWindowText(hwnd) SetForegroundWindow(hwnd) ShowWindow(hwnd, SW_RESTORE)
def foo(self, hwnd, mouse): # 去掉下面这句就所有都输出了,但是我不需要那么多 if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd): print(hwnd) if GetWindowText(hwnd) == 'IB Gateway': SetForegroundWindow(hwnd) print('ok') return
def GetWindByTitile(): """显示窗口(此处显示微信)""" from win32gui import FindWindow, SetForegroundWindow, ShowWindow, GetWindowText from win32con import SW_RESTORE hwnd = FindWindow("WeChatMainWndForPC", None) # text = GetWindowText(hwnd) SetForegroundWindow(hwnd) ShowWindow(hwnd, SW_RESTORE)
def Flash(): cur_foreground = GetForegroundWindow() ID = FindWindow(None, ttl) if ID == cur_foreground: SetForegroundWindow(taskbar) FlashWindowEx(ID, win32con.FLASHW_ALL | win32con.FLASHW_TIMERNOFG, 0, 0) #FlashWindowEx(ID, win32con.FLASHW_ALL, 500, 500) return
def change_focus(): global timerdone focused_window = GetForegroundWindow() print("[info]: switching focus to -> " + GetWindowText(focused_window)) while not timerdone: try: SetForegroundWindow(focused_window) except: pass
def Focus(window): def windowEnumerationHandler(hwnd, top_windows): top_windows.append((hwnd, GetWindowText(hwnd))) top_windows = [] EnumWindows(windowEnumerationHandler, top_windows) for i in top_windows: if window in i[1].lower(): ShowWindow(i[0], 5) SetForegroundWindow(i[0]) return
def Focus(window): def windowEnumerationHandler(hwnd, top_windows): top_windows.append((hwnd, GetWindowText(hwnd))) top_windows = [] info("Focus() scanning active windows") EnumWindows(windowEnumerationHandler, top_windows) for i in top_windows: if window in i[1].lower(): info("Focus() valid window found. focusing on window") ShowWindow(i[0],5) SetForegroundWindow(i[0]) return info("Focus() no valid window found")
def net_install(): ''' .net 3.5安装 :return: ''' while True: w = FindWindow(None, 'Windows 功能') if w > 0: break SetForegroundWindow(w) print(w) while True: b = FindWindowEx(w, None, 'Button', None) if b > 0: break print('%x,%x' % (w, b))
def hideSpotify(self) -> None: self.win.set_transparency(0) ShowWindow(self.win.handle, SW_SHOWNOACTIVATE) sleep(0.1) self.posY = self.base.rectangle().top SetWindowPos(self.win.handle, HWND_BOTTOM, 0, 0, 0, 0, BOTTOM_FLAGS) self.win.move_window(y=-50) if self.win.has_focus(): if self.hideloop > 9: self.hideloop = 0 try: SetForegroundWindow(DESKTOP_HWND) self.hideloop = 0 except: self.hideloop += 1 self.hideSpotify()
def captureAlbumArt(self): while (self.windowHandle != GetForegroundWindow()): SetForegroundWindow(self.windowHandle) time.sleep( WAIT_TIME) ## Give Spotify a moment to come to the foreground ShowWindow(self.windowHandle, SW_SHOWMAXIMIZED) time.sleep(WAIT_TIME) ## Give Spotify a second to become maximized ## Get the edges of the window left, top, right, bottom = GetWindowRect(self.windowHandle) left += self.artOffsets[0] bottom -= self.artOffsets[1] ## Get the album art's location from those edges and user specified offsets. region = (left, bottom - self.artSideLength, left + self.artSideLength, bottom) return pyscreenshot.grab(bbox=region, childprocess=False)
def on_zeroingButton_clicked(self): if self.flog == "flightButton": self.end_program("Test.exe") sleep(0.1) self.begin_program() sleep(0.1) # queue n = 2 tempList = [self.X, self.Y, self.H, self.psi, self.phi, self.theta] for i in tempList: getattr(i, "zeroingData")(n) # 反射 Y-theta都为零 self.updateTime() for i in range(0, len(data)): # 内存中的数也都为零 self.para[i] = 0.0 if self.is_web: # 重新加载地图 self.map.openURL() elif self.flog == "mainSystemButton": self.end_program("Test.exe") sleep(0.1) self.begin_program() sleep(0.1) # queue n = 2 tempList = [self.X, self.Y, self.H, self.psi, self.phi, self.theta] for i in tempList: getattr(i, "zeroingData")(n) # 反射 Y-theta都为零 self.updateTime() for i in range(0, len(data)): # 内存中的数也都为零 self.para[i] = 0.0 if self.is_web: # 重新加载地图 self.map.openURL() # 获取焦点 try: keybd_event(13, 0, 0, 0) SetForegroundWindow(self.hand) sleep(0.5) # 按下快捷键 keybd_event(115, 0, 0, 0) # F4键位码是115 sleep(0.01) keybd_event(115, 0, KEYEVENTF_KEYUP, 0) # 释放按键115 except UnboundLocalError: dlgTitle = u"打开错误" strInfo = u"打开Rhapsody程序打开错误" QMessageBox.critical(self, dlgTitle, strInfo)
def screenshot(window_title=None, factorx=0, factory=0): if window_title: hwnd = FindWindow(None, window_title) if hwnd: SetForegroundWindow(hwnd) x, y, x1, y1 = GetClientRect(hwnd) x, y = ClientToScreen(hwnd, (x, y)) x1, y1 = ClientToScreen(hwnd, (x1 - x, y1 - y)) # x,y,x1,y1 position and size x += int((x1 * factorx / 2)) x1 -= int((x1 * factorx)) y += int((y1 * factory / 2)) y1 -= int((y1 * factory)) im = pyautogui.screenshot(region=(x, y, x1, y1)) return im else: print('Window not found!') else: im = pyautogui.screenshot() return im
def tar(): ''' AutoCAD 2010解压安装 :return: ''' lable = 'AutoCAD 2010' while True: # 根据类名及标题名查询句柄 w = FindWindow(None, lable) if w > 0: break if w > 0: # 将软件窗口置于最前 SetForegroundWindow(w) # 更改解压路径 e = FindWindowEx(w, None, 'ComboBox', None) SendMessage(e, win32con.WM_SETTEXT, None, r'D:\Autodesk\AutoCAD_2010_Simplified_Chinese_MLD_WIN_64bit') # 开始解压 b = FindWindowEx(w, None, 'Button', 'Install') SendMessage(b, win32con.BM_CLICK, None, None) print('%x,%x,%x' % (w, e, b))
def handleConvert(self, event): dlg = Options() if os.name == 'nt': from win32gui import GetForegroundWindow, SetForegroundWindow aw = (GetForegroundWindow()) dlg.CenterOnScreen() dlg.ShowModal() SetForegroundWindow(aw) time.sleep(.3) if dlg.REPLACE: buffer = clipboard.copy() self.convert.setReplacer(dlg.REPLACE) self.convert.setGender(dlg.GENDER) buffer_new = self.convert.Process(buffer, dlg.DEBUG) clipboard.past(buffer_new[0], buffer_new[1])
def sendInput(self, event: Event, btn: O[int] = None) -> None: if isinstance(btn, int): if (0 <= event.x <= BTN_SIZE) and (0 <= event.y <= BTN_SIZE) and (0 <= btn <= 3): if btn == 0: self.spotify.win.send_keystrokes('^{LEFT}') elif 0 < btn < 3: self.spotify.win.send_keystrokes('{SPACE}') self.chngToStopped( ) if self.isPlaying else self.chngToPlaying() else: self.spotify.win.send_keystrokes('^{RIGHT}') else: if event.delta > 0: self.spotify.win.send_keystrokes('^{UP}') elif event.delta < 0: self.spotify.win.send_keystrokes('^{DOWN}') if self.spotifyMini and self.spotify.win.has_focus(): try: SetForegroundWindow(DESKTOP_HWND) except Exception: pass
def focus_on(name): count = 0 # search until found while True: count += 1 w = find_starting_with(name) press('alt') sleep(0.2) press_and_release('tab') release('alt') if w != 0: try: ShowWindow(w, 6) ShowWindow(w, 9) sleep(4) SetForegroundWindow(w) return 1 except Exception as e: print(e) sleep(0.5) if count > 20: print("ERROR: Couldn't find the browser tab.") return 0 sleep(0.5)
def SetForegroundWindow(self, hwnd): self.shell.SendKeys('%') SetForegroundWindow(hwnd)
def SetForegroundWindow(self, hwnd=None): if hwnd == None: hwnd = self.hwnd self.shell.SendKeys('%') SetForegroundWindow(hwnd)
def winDiscovery(self, appName=None, winTitle=None, beginTitle=None, skipTitle=None): """ support finding and focusing on application window or simple window title. Find the index and focuses on the first match of any of these. Applications within the application dictionary could have a number window_titles associated. """ wins = {} hwin = None index = None self.skipTitle = skipTitle # numerate windows into dictionary "wins" through callback function EnumWindows(self._callBack_popWin, wins) # clear the skip title that was passed into this function self.skipTitle = None total_windows = len(wins) # creating match lists for window titles namelist = [] partlist = [] if winTitle: namelist.append(winTitle) elif beginTitle: for v in wins.values(): if v.startswith(beginTitle): namelist.append(v) if appName: # trying to find window title of selected application within window # dictionary( local application context). Checking that the window # exists and it has supporting local application context (appDict) app = self.appDict[str(appName)] # app is an AppWindow object # checking if the window names is a list, handle string occurrence try: if app.winHandle: ShowWindow(int(hwin), 1) #SW_RESTORE) SetForegroundWindow(int(hwin)) #SetActiveWindow(int(hwin)) return (str(hwin), wins) except: pass # check if winNames is a list and add name to append to namelist if getattr(app.winNames, 'append', None): namelist = namelist + app.winNames else: namelist.append(app.winNames) # iterate through populated list of potential window titles for name in namelist: try: for title in wins.values(): if name in title: index = wins.values().index(title) break except: pass if index is not None: # logging.debug("index of application window: %s = %d" % # (wins[index],index)) hwin = (wins.keys())[index] logging.debug("Name: {0}, Handle: {1}".format( wins[hwin], str(hwin))) try: app.winHandle = hwin except: pass # ShowWindow and SetForegroundWindow are the recommended functions ShowWindow(int(hwin), 1) #SW_RESTORE) SetForegroundWindow(int(hwin)) #SetActiveWindow(int(hwin)) #app.winRect = wg.GetWindowRect(hwin) return (str(hwin), wins) else: return (None, wins)
from src.player_controller import PlayerController from src.keystate_manager import KeyboardInputManager import time from src.screen_processor import MapleScreenCapturer from src.screen_processor import StaticImageProcessor from win32gui import SetForegroundWindow wcap = MapleScreenCapturer() scrp = StaticImageProcessor(wcap) hwnd = wcap.ms_get_screen_hwnd() kbd_mgr = KeyboardInputManager() player_cntrlr = PlayerController(kbd_mgr, scrp) SetForegroundWindow(hwnd) time.sleep(0.5) scrp.update_image() print(scrp.get_minimap_rect()) print(scrp.find_player_minimap_marker()) player_cntrlr.update() print(player_cntrlr.x, player_cntrlr.y) #player_cntrlr.moonlight_slash_sweep_move(player_cntrlr.x + 100) player_cntrlr.optimized_horizontal_move(player_cntrlr.x + 1) #player_cntrlr.jumpr_double() #player_cntrlr.jumpr_glide() print(player_cntrlr.x, player_cntrlr.y)
def to_front(self): try: hwnd = find_window(title=self.name) SetForegroundWindow(hwnd) except WindowNotFoundError: pass
def showMainWindowFromMonitor(window): ShowWindow(window, 5) pressAlt() SetForegroundWindow(window)
import cv2, time, imutils, math, glob, random import numpy as np cap = MapleScreenCapturer() from win32gui import SetForegroundWindow x, y, w, h = 450, 180, 500, 130 ds = None while True: img = cap.capture(rect=[0, 0, 1600, 900], set_focus=False) img_arr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) final_img = imutils.resize(img_arr, width=200) cv2.imshow("s to save image", final_img) inp = cv2.waitKey(1) if inp == ord("s"): SetForegroundWindow(cap.ms_get_screen_hwnd()) time.sleep(0.3) ds = cap.capture(set_focus=False) ds = cv2.cvtColor(np.array(ds), cv2.COLOR_RGB2BGR) ds = ds[y:y + h, x:x + w] print("saved") elif inp == ord("q"): cv2.destroyAllWindows() break elif inp == ord("r"): imgpath = "C:\\Users\\tttll\\PycharmProjects\\MacroSTory\\rune_trainer\\images\\screenshots\\finished\\*.png" dt = random.choice(glob.glob(imgpath)) ds = cv2.imread(dt) print("read data")
def show_maximized(self, hwnd=None): if hwnd is None: hwnd = self.hwnd self.shell.SendKeys('%') SetForegroundWindow(hwnd)
def on_mainSystemButton_clicked(self): # 打开主面板 # 打开rhapsody软件 if path.isfile(self.RhapsodyPath) and path.isfile( self.RhapsodyProjectPath): if "rhapsody" in self.RhapsodyPath.lower( ) and '.rpy' in self.RhapsodyProjectPath: # win32api.ShellExecute(0, 'open', self.RhapsodyPath, self.RhapsodyProjectPath, '', 1) Rhapsody = Popen([self.RhapsodyPath, self.RhapsodyProjectPath]) print(Rhapsody) # print("打开rhapsody成功!!!") else: curPath = QDir.currentPath() dlgTitle = u"打开Rhapsody软件" filt = u"执行程序(*.exe);;所有文件(*.*)" filename, _ = QFileDialog.getOpenFileName(self, dlgTitle, curPath, filt) if "sublime_text" in filename.lower(): Rhapsody = Popen([filename]) elif filename == '': pass else: dlgTitle = u"打开错误" strInfo = u"请打开Rhapsody程序" QMessageBox.critical(self, dlgTitle, strInfo) sleep(self.openRhapsodyTime) # 5秒 #打开工程编译的.exe文件 if path.isfile(self.RhapsodyProjectExePath): if '.exe' in self.RhapsodyProjectExePath: ShellExecute(0, 'open', self.RhapsodyProjectExePath, "", '', 1) # print("打开rhapsody成功!!!") else: curPath = QDir.currentPath() dlgTitle = u"打开Rhapsody项目编译之后可执行文件" filt = u"执行程序(*.exe);;所有文件(*.*)" filename, _ = QFileDialog.getOpenFileName(self, dlgTitle, curPath, filt) if ".exe" in filename.lower(): ShellExecute(0, 'open', filename, "", '', 1) elif filename == '': pass else: dlgTitle = u"打开错误" strInfo = u"打开Rhapsody项目编译之后可执行文件" QMessageBox.critical(self, dlgTitle, strInfo) sleep(self.openRhapsodyExeTime) # 这个时间是等待Rhapsody加载工程 # TODO: 模拟键盘发送一个F4, 问题怎么把软件的焦点防御rhapsody # 先获取焦点 hand = None try: for hwnd in get_hwnds_for_pid(Rhapsody.pid): print(hwnd, "=>", GetWindowText(hwnd)) keybd_event(13, 0, 0, 0) hand = hwnd SetForegroundWindow(hwnd) sleep(0.1) # 按下快捷键 keybd_event(115, 0, 0, 0) #F4键位码是115 sleep(0.01) keybd_event(115, 0, KEYEVENTF_KEYUP, 0) #释放按键115 break except UnboundLocalError: dlgTitle = u"打开错误" strInfo = u"打开Rhapsody程序打开错误" QMessageBox.critical(self, dlgTitle, strInfo) sleep(0.5) mainWindow = MainWindow("mainSystemButton", hand) mainWindow.start()
def get_wind_by_title(name): """显示窗口""" hwnd = FindWindow(None, name) # text = GetWindowText(hwnd) SetForegroundWindow(hwnd) ShowWindow(hwnd, SW_RESTORE)