def _set_foreground_window(self, acc_idx, minimize_current=False): # Delay time.sleep(SWAP_DELAY) # Maximize wanted window hwnd_cur = self.acc_idx_hwnd[acc_idx] if not gui.IsIconic(hwnd_cur): print("not min", acc_idx) gui.ShowWindow(hwnd_cur, con.SW_SHOWMINIMIZED) gui.ShowWindow(hwnd_cur, con.SW_RESTORE) # Minimize current window if minimize_current: prev_acc_idx = self.last_foreground_acc_idx if prev_acc_idx is not None: hwnd_prev = self.acc_idx_hwnd[prev_acc_idx] if hwnd_prev and not gui.IsIconic(hwnd_prev): gui.ShowWindow(hwnd_prev, con.SW_SHOWMINIMIZED) # Minimize window after wanted to prevent min+max at the same time # on the next step if minimize_current: next_acc_idx = self._get_next_acc_idx(acc_idx) if next_acc_idx is not None: hwnd_next = self.acc_idx_hwnd.get(next_acc_idx, None) if hwnd_next and not gui.IsIconic(hwnd_next): gui.ShowWindow(hwnd_next, con.SW_SHOWMINIMIZED) self.last_foreground_acc_idx = acc_idx self.last_swap_end = time.time()
def testss(): # 获取窗口大小 hwnd = win32gui.FindWindow(qq_or_wx, winname) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 500, 500, win32con.SWP_SHOWWINDOW) win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL) if win32gui.IsIconic(hwnd): logger(">>>窗口已经最小化了") win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL) time.sleep(0.1) logger(">>>开始虚拟按键操作") logger(">>>开始虚拟按键操作") win32gui.SetForegroundWindow(hwnd) # 设置剪贴板 win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32con.CF_UNICODETEXT, "123") win32clipboard.CloseClipboard() time.sleep(0.1) # 填充消息 win32gui.PostMessage(hwnd, win32con.WM_CHAR, 22, 2080193) win32gui.PostMessage(hwnd, win32con.WM_PASTE, 0, 0) time.sleep(0.1) # 回车发送消息 win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0) time.sleep(0.1) # 清空剪贴板 win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.CloseClipboard() time.sleep(0.5)
def restore_window_if_minimized(handle): window = win32gui.FindWindow( None, 'oneboss - erp.oneboss.com.br:10003 - ' 'Conexão de Área de Trabalho Remota') is_minimized = win32gui.IsIconic(window) if is_minimized: win32gui.ShowWindow(window, win32con.SW_SHOWNOACTIVATE)
def __call__(self, ensoapi, window=None): if window is None: return None logging.debug("Go to window '%s'" % window) for hwnd, title in self.windows: title = xml.sax.saxutils.escape(title).lower() if title == window: try: #windowPlacement = win32gui.GetWindowPlacement(hwnd) #showCmd = windowPlacement[1] #print showCmd #if showCmd == SW_RESTORE: # win32gui.ShowWindow(hwnd, SW_RESTORE) #else: # win32gui.BringWindowToTop(hwnd) if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) win32gui.SetForegroundWindow(hwnd) except Exception, e: if e[0] == 0: time.sleep(0.2) try: win32gui.SetForegroundWindow(hwnd) except Exception, e: time.sleep(0.2) try: win32gui.BringWindowToTop(hwnd) except Exception, e: pass elif e[0] == 2: pass
def _should_track_window(self, hwnd): # TODO: why Photos not tracked? # check ignored classes try: classname = win32gui.GetClassName(hwnd) except: return False if classname in config.ignored_classnames(): return False # check bad styling try: style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE) except: return False if not style & win32con.WS_MAXIMIZEBOX or style & win32con.WS_POPUP: return False # check visibility try: visible = win32gui.IsWindowVisible(hwnd) iconic = win32gui.IsIconic(hwnd) zoomed = ctypes.windll.user32.IsZoomed(hwnd) except: return False return visible and not iconic and not zoomed
def switch_to2(window_ID): print "moving" if win32gui.IsIconic(window_ID): print "undoing" print win32gui.ShowWindow(window_ID, win32con.SW_RESTORE) print win32gui.SetForegroundWindow(window_ID) return True
def game_state(): """ Return GameState Enum """ # Get handle for Mindustry window win_hd = win32gui.FindWindow(None, "Mindustry") if win_hd == 0: return GameState.NOT_FOUND if win32gui.IsIconic(win_hd): return GameState.MINIMIZED # Create device context win_dc = win32gui.GetWindowDC(win_hd) img_dc = win32ui.CreateDCFromHandle(win_dc) # Create memory based device context mem_dc = img_dc.CreateCompatibleDC() # Create bitmap object bitmap = win32ui.CreateBitmap() bitmap.CreateCompatibleBitmap(img_dc, Notifier.SCREENSHOT_X2, Notifier.SCREENSHOT_Y2) mem_dc.SelectObject(bitmap) result = windll.user32.PrintWindow(win_hd, mem_dc.GetSafeHdc(), 1) bitmap_info = bitmap.GetInfo() bitmap_str = bitmap.GetBitmapBits(True) img = Image.frombuffer( "RGB", (bitmap_info["bmWidth"], bitmap_info["bmHeight"]), bitmap_str, "raw", "BGRX", 0, 1) img_cropped = img.crop( (Notifier.SCREENSHOT_X1, Notifier.SCREENSHOT_Y1, Notifier.SCREENSHOT_X2, Notifier.SCREENSHOT_Y2)) # Check for boss state = GameState.BOSS_WAVE width = Notifier.SCREENSHOT_X2 - Notifier.SCREENSHOT_X1 height = Notifier.SCREENSHOT_Y2 - Notifier.SCREENSHOT_Y1 for i in range(1, width): for j in range(1, height): pixel = img_cropped.getpixel((i, j)) if not Notifier.is_boss_pixel(pixel): state = GameState.OTHER break else: continue # only executed if no break encountered break win32gui.DeleteObject(bitmap.GetHandle()) try: mem_dc.DeleteDC() img_dc.DeleteDC() except Exception as err: print(f"Error trying to delete context: {err}") win32gui.ReleaseDC(win_hd, win_dc) if result != 1: return GameState.SCREENSHOT_FAIL return state
def IsFocused(self): if win32gui.IsIconic(self.hwnd): win32gui.ShowWindow(self.hwnd, win32con.SW_RESTORE) return False elif self.hwnd != win32gui.GetForegroundWindow(): return False else: return True
def switch_to_window_focus(window: int): """responsible for maximizing or restoring windows when selected""" #win32gui.ShowWindow(window, win32con.SW_RESTORE) #win32gui.BringWindowToTop(window) # - check if the window is minimized in the tray. # if so then we need to restore the window if (win32gui.IsIconic(window)): win32gui.ShowWindow(window, win32con.SW_RESTORE) win32gui.SetForegroundWindow(window)
def windowEnumerationHandler(hwnd, top_windows): if win32gui.IsWindowVisible(hwnd) and not win32gui.IsIconic(hwnd): if (win32gui.GetWindowText(hwnd) != ''): top_windows.append((hwnd, win32gui.GetWindowText(hwnd))) ss = win32gui.GetWindowPlacement(hwnd) if (ss[4][0] < 0): second_monitor.append((hwnd, ss[4])) else: main_monitor.append((hwnd, ss[4]))
def is_window_minimized(hwnd): """ @param hwnd HWND @reutrn bool """ try: return bool(win32gui.IsIconic(hwnd)) except: return False
def getWindow_Img_new(self, Emu_Index): self.Hwnd = int(self.Get_Self_Hawd(Emu_Index)) # 將 hwnd 換成 WindowLong s = win32gui.GetWindowLong(self.Hwnd, win32con.GWL_EXSTYLE) win32gui.SetWindowLong(self.Hwnd, win32con.GWL_EXSTYLE, s | win32con.WS_EX_LAYERED) # 判斷視窗是否最小化 show = win32gui.IsIconic(self.Hwnd) # 將視窗圖層屬性改變成透明 # 還原視窗並拉到最前方 # 取消最大小化動畫 # 取得視窗寬高 if show == 1: win32gui.SystemParametersInfo(win32con.SPI_SETANIMATION, 0) win32gui.SetLayeredWindowAttributes(self.Hwnd, 0, 0, win32con.LWA_ALPHA) win32gui.ShowWindow(self.Hwnd, win32con.SW_RESTORE) x, y, width, height = self.getWindow_W_H(self.Hwnd) # 創造輸出圖層 hwindc = win32gui.GetWindowDC(self.Hwnd) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() # 取得視窗寬高 x, y, width, height = self.getWindow_W_H(self.Hwnd) # 如果視窗最小化,則移到Z軸最下方 if show == 1: win32gui.SetWindowPos(self.Hwnd, win32con.HWND_BOTTOM, x, y, width, height, win32con.SWP_NOACTIVATE) # 複製目標圖層,貼上到 bmp bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (8, 3), win32con.SRCCOPY) # 將 bitmap 轉換成 np signedIntsArray = bmp.GetBitmapBits(True) img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height, width, 4) #png,具有透明度的 # 釋放device content srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(self.Hwnd, hwindc) win32gui.DeleteObject(bmp.GetHandle()) # 還原目標屬性 if show == 1: win32gui.SetLayeredWindowAttributes(self.Hwnd, 0, 255, win32con.LWA_ALPHA) win32gui.SystemParametersInfo(win32con.SPI_SETANIMATION, 1) # 回傳圖片 #src_img = img #src_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #src_img = cv2.imwrite('test1.jpg',img) #self.ScreenHot = img return img
def enum_handler(hwnd, results): results[hwnd] = { "title": win32gui.GetWindowText(hwnd), "visible": win32gui.IsWindowVisible(hwnd), "minimized": win32gui.IsIconic(hwnd), "rectangle": win32gui.GetWindowRect(hwnd), # (left, top, right, bottom) "next": win32gui.GetWindow( hwnd, win32con.GW_HWNDNEXT) # Window handle to below window }
def movetocenter(): hw = win32gui.FindWindow('BS2CHINAUI', 'BlueStacks App Player') if win32gui.IsIconic(hw): win32gui.ShowWindow(hw, win32con.SW_SHOWNORMAL) win32gui.SetForegroundWindow(hw) tmp = win32gui.GetWindowRect(hw) x0, y0, x1, y1 = tmp x = (x1 - x0) / 2 + x0 y = (y1 - y0) / 2 + y0 pag.moveTo(x, y, duration=1)
def set_foreground_window(hwnd): try: if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) if win32gui.IsWindowVisible(hwnd) == 0: win32gui.ShowWindow(hwnd, win32con.SW_SHOW) win32gui.SetForegroundWindow(hwnd) except pywintypes.error as e: log.debug("Could not bring window to front '{}'".format(e.strerror))
def ReportOnTime(Time): msg = 'currnet time is ' winname = 'Tips' tk.messagebox.showinfo(winname, message=msg + Time) handle = win32gui.FindWindow(None, 'MainPage') if (win32gui.IsIconic(handle)): ret = win32gui.ShowWindow(handle, win32con.SW_SHOWNORMAL) # ret = win32gui.ShowWindow(handle, win32con.SW_RESTORE) # win32gui.SetForegroundWindow(handle) time.sleep(1)
def print_screen(window_title, left, top, right, bottom): handle = get_window_handle(window_title) while (win32gui.IsIconic(handle)): pass sleep(0.5) (x1, y1, x2, y2) = get_window_pos(handle) img = ImageGrab.grab((x1, y1, x2, y2)) weight, height = img.size box = (weight*left, height*top, weight*right, height*bottom) img = img.crop(box) return img
def get_windowstate(hwnd): statu = "正常" if not gui.IsWindowVisible(hwnd): statu = "隐藏" if gui.IsIconic(hwnd): statu = "最小化" if (gui.GetWindowLong(hwnd, con.GWL_EXSTYLE) & con.WS_EX_TOPMOST) != 0: statu = "置顶" if gui.GetForegroundWindow() == hwnd: statu = "活动窗口" return statu
def window_location(): """Finds the location of the League window on the desktop""" try: league_win = winGuiAuto.findTopWindow("League of Legends") except: return None if win32gui.IsWindowVisible(league_win) and not win32gui.IsIconic(league_win): win_loc = win32gui.GetWindowPlacement(league_win)[-1] return win_loc else: return None
def raise_window_by_win_id(window_id): """The first window which windowId matches the given windowId in the variable will be raised to the front of the gui""" wins = [] win32gui.EnumWindows(lambda x, y: y.append(x), wins) for win_id in wins: if win_id == window_id: if win32gui.IsIconic(win_id): win32gui.ShowWindow(win_id, win32con.SW_RESTORE) win32gui.SetForegroundWindow(win_id) break
def pop_window(name): handle = win32gui.FindWindow(0, name) if handle == 0: return False else: win32gui.SendMessage(handle, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0) win32gui.SetForegroundWindow(handle) while (win32gui.IsIconic(handle)): continue return True
def callback(hwnd, ids): if not isRealWindow(hwnd): return if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_NORMAL) rect = win32gui.GetWindowRect(hwnd) windows.loc[hwnd, 'x'] = rect[0] windows.loc[hwnd, 'y'] = rect[1] windows.loc[hwnd, 'width'] = rect[2] - windows.loc[hwnd, 'x'] windows.loc[hwnd, 'height'] = rect[3] - windows.loc[hwnd, 'y'] windows.loc[hwnd, 'title'] = win32gui.GetWindowText(hwnd)
def raise_window_by_name(title): """The first window which title machtes the name given in the variable title will be raised to the front of the gui""" wins = [] win32gui.EnumWindows(lambda x, y: y.append(x), wins) for win_id in wins: win_name = win32gui.GetWindowText(win_id) if title in win_name.lower(): if win32gui.IsIconic(win_id): win32gui.ShowWindow(win_id, win32con.SW_RESTORE) win32gui.SetForegroundWindow(win_id) break
def set_current_window(cls, hwnd): """ 将指定的窗口设置为当前窗口 Args: hwnd (int): 指定的窗口句柄 Returns: None """ if win32gui.IsIconic(hwnd): # 如果窗口被最小化了,先恢复 win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) win32gui.SetForegroundWindow(hwnd)
def activate(self, handle=''): ''' It is important to choose the right flag, the window may not be shown otherwise. ''' if win32gui.IsIconic(handle): win32gui.ShowWindow(handle, win32con.SW_RESTORE) elif win32gui.GetWindowPlacement(handle)[1] in ( win32con.SW_SHOWMAXIMIZED, win32con.SW_MAXIMIZE): win32gui.ShowWindow(handle, win32con.SW_MINIMIZE) win32gui.ShowWindow(handle, win32con.SW_RESTORE) else: win32gui.ShowWindow(handle, win32con.SW_SHOW) win32gui.SetForegroundWindow(handle)
def find_img(self, part_name, accuracy=0.9): if not self.hwnd or win32gui.IsIconic(self.hwnd): # 窗口不存在或最小化 return None img = self.screen_shot() img_mat = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR) match = aircv.find_template(img_mat, self.imgs[part_name]) if match is None: return None elif match['confidence'] < accuracy: # print(part_name, 'not exact, confidence is: ', match['confidence']) return None elif match['confidence'] >= accuracy: print(part_name + ' is found, accuracy: ', match['confidence']) return match['result']
def game_screenshot(self): if not win32gui.IsIconic(self.hwnd): # check whether the window is minize or not width, height = self.get_shape() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(self.mfcDC, width, height) self.saveDC.SelectObject(saveBitMap) self.saveDC.BitBlt((0, 0), (width, height), self.mfcDC, (0, 0), win32con.SRCCOPY) signedIntsArray = saveBitMap.GetBitmapBits(True) im_opencv = numpy.fromstring(signedIntsArray, dtype='uint8') im_opencv.shape = (height, width, 4) # logger.info('screenshot shape: {0}'.format(im_opencv.shape)) win32gui.DeleteObject(saveBitMap.GetHandle()) return cv2.cvtColor(im_opencv, cv2.COLOR_BGRA2GRAY)
def focus(self): ''' bring a window foreground ''' hwnd = self.hwnd if (win32gui.GetForegroundWindow() != hwnd): if (not win32gui.IsIconic(hwnd)): win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE) win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL) # 重新取得視窗位置 rect = win32gui.GetWindowRect(hwnd) self.rect = rect
def CaptureWindow(hwnd, topMargin=0, bottomMargin=0, leftMargin=0, rightMargin=0, scale=1.0): user32 = windll.user32 user32.SetProcessDPIAware() hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() left, top, right, bot = win32gui.GetWindowRect(hwnd) w = right - left h = bot - top if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE) left, top, right, bot = win32gui.GetWindowRect(hwnd) w = right - left h = bot - top # if (not win32gui.IsWindowVisible(hwnd)) or w < 200 or h < 200: # win32gui.ShowWindow(hwnd, win32con.WM_SHOWWINDOW) # win32gui.SetForegroundWindow(hwnd) # # left, top, right, bot = win32gui.GetWindowRect(hwnd) # w = right - left # h = bot - top saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) imCrop = ImageOps.crop(im, (leftMargin, topMargin, rightMargin, bottomMargin)) if scale != 1.0: imCrop = imCrop.resize( (int(imCrop.width * scale), int(imCrop.height * scale)), Image.BICUBIC) return imCrop
def find_all_imgs(self, part_name, accuracy=0.9): if not self.hwnd or win32gui.IsIconic(self.hwnd): # 窗口不存在或最小化 return None img = self.screen_shot() img_mat = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR) # img_mat = aircv.imread('screenshot.png') matches = aircv.find_all_template(img_mat, self.imgs[part_name]) positions = [] for match in matches: if match['confidence'] < accuracy: continue positions.append(match['result']) # draw_circle(img_mat, positions, 60, (20, 200, 20), 3) return positions