def open_windows(coc_clan_dict): #打开QQ和wechat会话窗口,发送消息 try: qq_hwnd = win32gui.FindWindow(None, 'QQ') wechat_hwnd = win32gui.FindWindow(None, '微信') print("捕捉到QQ主窗体的句柄为:" + str(qq_hwnd)) print("捕捉到微信主窗体的句柄为:" + str(wechat_hwnd)) win32gui.ShowWindow(qq_hwnd, win32con.SW_SHOW) #win32gui.ShowWindow(wechat_hwnd,win32con.SW_SHOW) print("正在打开会话窗口...\n") time.sleep(1) for coc_clan_name in coc_clan_dict: #打开会话窗口 setText(coc_clan_name) win32api.keybd_event(13, 0, 0, 0) win32gui.SetForegroundWindow(qq_hwnd) win32gui.SetActiveWindow(qq_hwnd) time.sleep(1) win32gui.SendMessage(qq_hwnd, 770, 0, 0) time.sleep(1) win32gui.SetForegroundWindow(qq_hwnd) win32gui.SetActiveWindow(qq_hwnd) win32api.keybd_event(0x0D, win32api.MapVirtualKey(0x0D, 0), 0, 0) win32api.keybd_event(0x0D, win32api.MapVirtualKey(0x0D, 0), win32con.KEYEVENTF_KEYUP, 0) #发送信息 send_qq(coc_clan_dict[coc_clan_name]) except: print("没有找到QQ或微信程序")
def send_qq(message): #发送消息给QQ用户 setText(message) hwnd_title = dict() def get_all_hwnd(hwnd, mouse): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)}) win32gui.EnumWindows(get_all_hwnd, 0) for h, t in hwnd_title.items(): if t != "": hwnd = win32gui.FindWindow('TXGuiFoundation', t) # 获取qq窗口句柄 if hwnd != 0: #win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0) #虽然可以还原最小化的会话窗口,但经过测试发现并不能解决还原后不发送消息的问题。 win32gui.ShowWindow(hwnd, win32con.SW_SHOW) time.sleep(1) win32gui.SetForegroundWindow(hwnd) win32gui.SetActiveWindow(hwnd) time.sleep(1) win32gui.SendMessage(hwnd, 770, 0, 0) # 将剪贴板文本发送到QQ窗体 win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) #模拟按下回车键 win32gui.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0) #模拟松开回车键
def right(): global shell shell = win32com.client.Dispatch('WScript.Shell') win32gui.SetForegroundWindow(inputWindow) win32gui.SetActiveWindow(inputWindow) #root.after(3000,typeright) typeright()
def get_windows(window_title): # 获取窗口 hwnd = win32gui.FindWindow(win32con.NULL, window_title) if hwnd == 0: error_exit('"%s" not found' % window_title) # 前置 + 激活 win32gui.SetForegroundWindow(hwnd) win32gui.SetActiveWindow(hwnd) # 获取屏幕分辨率 screen_width, screen_height = get_screen_size() window_left, window_top, window_right, window_bottom =\ win32gui.GetWindowRect(hwnd) print('游戏窗口坐标:\n\tleft,top = {0},{1}\n\tright,bottom = \ {2},{3}'.format(window_left, window_top, window_right, window_bottom)) if min(window_left, window_top) < 0\ or window_right > screen_width\ or window_bottom > screen_height: error_exit('window is at wrong position') """ window_width = window_right - window_left window_height = window_bottom - window_top print('----- 程序窗口尺寸 -----') print('窗口尺寸:\nwidth,height = {0},{1}'.format( window_width, window_height)) """ # 获取左上角坐标 return (window_left, window_top)
def showTweditWindowInForeground1(): # documentaiton of win32con window flags and win32gui showWindow functions # style=win32con.SW_SHOWNORMAL : int # Specifies how the window is to be shown. It must be one of win32con.SW_HIDE, win32con.SW_MINIMIZE, # win32con.SW_RESTORE, win32con.SW_SHOW, win32con.SW_SHOWMAXIMIZED win32con.SW_SHOWMINIMIZED, win32con. # SW_SHOWMINNOACTIVE, win32con.SW_SHOWNA, win32con.SW_SHOWNOACTIVATE, or win32con.SW_SHOWNORMAL import win32gui import win32con handle = [] win32gui.EnumWindows(win_enum_callback_twedit, handle) if len(handle): # win32gui.SetForegroundWindow(handle[0]) win32gui.SetActiveWindow(handle[0]) win32gui.BringWindowToTop(handle[0]) win32gui.SetFocus(handle[0]) win32gui.ShowWindow(handle[0], win32con.SW_RESTORE)
def showTweditWindowWithPIDInForeground(_pid): # documentaiton of win32con window flags and win32gui showWindow functions # style=win32con.SW_SHOWNORMAL : int # Specifies how the window is to be shown. It must be one of win32con.SW_HIDE, win32con.SW_MINIMIZE, win32con.SW_RESTORE, win32con.SW_SHOW, win32con.SW_SHOWMAXIMIZED win32con.SW_SHOWMINIMIZED, win32con.SW_SHOWMINNOACTIVE, win32con.SW_SHOWNA, win32con.SW_SHOWNOACTIVATE, or win32con.SW_SHOWNORMAL import win32gui import win32con import win32process handle = [] win32gui.EnumWindows(win_enum_callback_twedit, handle) # try: # dbgMsg("this is twedit window handle,",handle[0]) # except IndexError,e: # print "problem with getting window handle" print "HANDLE ELELMENTS:", len(handle) # pid=win32process.GetCurrentProcessId() for hwnd in handle: t, p = win32process.GetWindowThreadProcessId(hwnd) print "t=", t, " p=", p print "pid=", _pid # pid = win32process.GetProcessId() # print "pid=",pid if _pid == p: win32gui.SetActiveWindow(hwnd) win32gui.BringWindowToTop(hwnd) # this does not work on windows Vista dna windows 7 # win32gui.SetFocus(hwnd) win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) win32gui.SetForegroundWindow(hwnd)
def display_room_rect(left_top_x, left_top_y, right_bot_x, right_bot_y): hWnd = win32gui.FindWindow(None, "QQ游戏 - 连连看角色版") win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) hDC = win32gui.GetWindowDC(hWnd) rect = win32gui.GetWindowRect(hWnd) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y print("Window name: " + win32gui.GetWindowText(hWnd)) print("Window hDC: " + str(hDC)) print("x, y, w, h == " + str(x) + " " + str(y) + " " + str(w) + " " + str(h) + " ") image = np.zeros( (right_bot_y - left_top_y + 1, right_bot_x - left_top_x + 1, 3)) for y in range(right_bot_y - left_top_y + 1): #h for x in range(right_bot_x - left_top_x + 1): #w image[y, x] = np.asarray( Int2RGB(win32gui.GetPixel(hDC, x + left_top_x, y + left_top_y))) / 255 win32gui.ReleaseDC(hWnd, hDC) plt.imshow(image[..., ::-1]) # GetPixel得到的是BGR而不是RGB,所以需要转换一下 plt.show()
def ClickButton(button_hwnd): """Clicks a button window by sending a BM_CLICK message. Per http://msdn2.microsoft.com/en-us/library/bb775985.aspx "If the button is in a dialog box and the dialog box is not active, the BM_CLICK message might fail. To ensure success in this situation, call the SetActiveWindow function to activate the dialog box before sending the BM_CLICK message to the button." Args: button_hwnd: HWND to the button to be clicked. """ previous_active_window = win32gui.SetActiveWindow(button_hwnd) win32gui.PostMessage(button_hwnd, win32con.BM_CLICK, 0, 0) if previous_active_window: win32gui.SetActiveWindow(previous_active_window)
def set_active_window(hwnd): """Within current thread @param hwnd HWND """ try: return bool(win32gui.SetActiveWindow(hwnd)) except: return False
def set_active_window(window_id): if get_windows_placement(window_id) == 2: win32gui.ShowWindow(window_id, SW_RESTORE) else: win32gui.ShowWindow(window_id, SW_SHOW) win32gui.SetForegroundWindow(window_id) win32gui.SetActiveWindow(window_id)
def main(): # 这个状态机实际上不健壮,万一出现进入房间超时等意外状态,程序即陷入错误 status = GameState.GS_INLOBBY waitting_time = 0 while True: if status == GameState.GS_INLOBBY: enter_room_from_lobby() elif status == GameState.GS_INROOM: if waitting_time == 0: click_start() waitting_time = 1 elif waitting_time < 20: time.sleep(1) waitting_time += 1 print("等待{}秒...".format(waitting_time)) else: exit_room() elif status == GameState.GS_INGAME: print("准备开始游戏") time.sleep(2) # 一开始方块没有出现,等待两秒 # solve_game_by_brute_force() solve_game_with_grace() time.sleep(2) exit_room() pre_status = status status = get_status() print("现在状态:{}".format(status)) # 退出room内等待状态后清零计时 if pre_status == GameState.GS_INROOM and status != GameState.GS_INROOM: waitting_time = 0 # 遇到未知情况时尝试重新恢复窗口焦点恢复运行,无法保证必然有效 if status == GameState.GS_UNKNOWN: hWnd = win32gui.FindWindow(None, "QQ游戏 - 连连看角色版") if hWnd == 0: hWnd = get_lobby_hWnd() assert hWnd != 0 win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) status = GameState.GS_INLOBBY continue else: win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) status = GameState.GS_INROOM
def maximize_bwindow(bwindow): win32gui.SetActiveWindow(bwindow) try: win32gui.SetForegroundWindow(bwindow) except Exception: raise (MeetException("Unable to set foreground window")) else: win32gui.ShowWindow(bwindow,win32con.SW_MAXIMIZE) time.sleep(5)
def open_and_ID(prog_ID, win_ID): program_handle = win32com.client.Dispatch(prog_ID) app_ID = wg.FindWindow(None, win_ID) wg.ShowWindow(app_ID, win32con.SW_MAXIMIZE) wg.SetActiveWindow(app_ID) wg.SetForegroundWindow(app_ID) #print(program_handle) print(app_ID) return program_handle
def click_piece(x, y, speed_corrector): hWnd = win32gui.FindWindow(None, "QQ游戏 - 连连看角色版") win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) transferred_x, transferred_y = 9 + x * 31 + 13, 180 + y * 35 + 13 lParam = win32api.MAKELONG(transferred_x, transferred_y) win32gui.SendMessage(hWnd, win32con.WM_LBUTTONDOWN, 0, lParam) win32gui.SendMessage(hWnd, win32con.WM_LBUTTONUP, 0, lParam) time.sleep(BURTE_FORCE_GAME_SPEED + random.random() * speed_corrector)
def __set_active_window(self, window_id): """make window active""" if self.__get_windows_placement(window_id) == 2: win32gui.ShowWindow(window_id, SW_RESTORE) else: win32gui.ShowWindow(window_id, SW_SHOW) win32gui.SetForegroundWindow(window_id) win32gui.SetActiveWindow(window_id) return
def for_debug(): hWnd = win32gui.FindWindow(None, "QQ游戏 - 连连看角色版") win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) hDC = win32gui.GetWindowDC(hWnd) print(Int2RGB(win32gui.GetPixel(hDC, 605, 588))) print(get_status()) win32gui.ReleaseDC(hWnd, hDC)
def activate_window(hwnd): global Shell Shell.SendKeys('%') pid = win32process.GetWindowThreadProcessId(hwnd)[1] windll.user32.AllowSetForegroundWindow(pid) win32gui.ShowWindow(hwnd, win32con.SW_SHOW) win32gui.BringWindowToTop(hwnd) win32gui.SetActiveWindow(hwnd) windll.user32.SwitchToThisWindow(hwnd, 1) win32gui.SetForegroundWindow(hwnd)
def focusDofusWindow(account_name=None): if not account_name: DOFUS_HWND = pywinauto.findwindows.find_windows( title_re=".*Dofus.*")[0] else: DOFUS_HWND = pywinauto.findwindows.find_windows( title_re=f".*{account_name}.*")[0] win32gui.SetForegroundWindow(DOFUS_HWND) win32gui.SetActiveWindow(DOFUS_HWND) win32gui.ShowWindow(DOFUS_HWND, win32con.SW_MAXIMIZE)
def onCUI(self, event): global hide_mode if(hide_mode == False): hide_mode = True win32gui.ShowWindow(hwnd, win32con.SW_HIDE) else: hide_mode = False win32gui.ShowWindow(hwnd, win32con.SW_SHOW) win32gui.SetActiveWindow(hwnd) win32gui.SetForegroundWindow(hwnd)
def bring_to_front(hwnd): user32 = ctypes.WinDLL("user32") user32.SetWindowPos.restype = wintypes.HWND user32.SetWindowPos.argtypes = [ wintypes.HWND, wintypes.HWND, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.UINT ] user32.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, 0x0001) win32gui.SetActiveWindow(hwnd)
def goToWindow(self, hwnd): windowPlacement = win32gui.GetWindowPlacement(hwnd) showCmd = windowPlacement[1] if showCmd == SW_RESTORE: win32gui.ShowWindow(hwnd, SW_RESTORE) else: win32gui.BringWindowToTop(hwnd) win32gui.SetForegroundWindow(hwnd) win32gui.SetActiveWindow(hwnd)
def window_set_foreground(hwnd): """Bring a window to the foreground and activate it. :param hwnd: Hwnd of window """ try: win32gui.SetForegroundWindow(hwnd) win32gui.BringWindowToTop(hwnd) win32gui.SetActiveWindow(hwnd) except Exception as ex: logger.warning(ex)
def _goToWindow(self, hwnd): # Bascially copied from old Go-Y plugin windowPlacement = win32gui.GetWindowPlacement(hwnd) showCmd = windowPlacement[1] if showCmd == SW_RESTORE: win32gui.ShowWindow(hwnd, SW_RESTORE) else: win32gui.BringWindowToTop(hwnd) win32gui.SetForegroundWindow(hwnd) win32gui.SetActiveWindow(hwnd)
def start(): """ Startet WMP wenn dieses noch nicht gestarted wurde. Wenn dieser bereits gestartet wurde, wird er in den Vordergrund gesetzt. """ wmpWindow = eg.WindowMatcher('wmplayer.exe', 'Windows Media Player')() import win32gui if not wmpWindow : eg.plugins.System.Execute(u'C:\\Program Files (x86)\\Windows Media Player\\wmplayer.exe') else: window = wmpWindow[0] win32gui.SetForegroundWindow(window) win32gui.SetActiveWindow(window)
def set_focus_on_window(hwnd): """Bring a window to the foreground :param hwnd: hwnd of window """ if window_exist_by_hwnd(hwnd): win32gui.SetForegroundWindow(hwnd) win32gui.BringWindowToTop(hwnd) win32gui.SetActiveWindow(hwnd) return True else: logger.debug('Could not find the HWND: {}'.format(hwnd)) return False
def gotold(hwnd): if not win32gui.IsWindow(hwnd): return _, showCmd, _, _, _ = win32gui.GetWindowPlacement(hwnd) if showCmd == SW_SHOWMINIMIZED: win32gui.ShowWindow(hwnd, SW_RESTORE) else: win32gui.ShowWindow(hwnd, SW_SHOW) win32gui.SetForegroundWindow(hwnd) win32gui.SetActiveWindow(hwnd)
def start(): """ Startet VLC wenn dieses noch nicht gestarted wurde. Falls dieses bereits gestartet wurde, wird es in den Vordergrund gesetzt. """ vlcWindow = eg.WindowMatcher('vlc.exe', '{*} - VLC media player')() import win32gui if not vlcWindow: eg.plugins.System.Execute(u'C:\\Program Files\\VideoLAN\\VLC\\vlc.exe') else: window = vlcWindow[0] win32gui.SetForegroundWindow(window) win32gui.SetActiveWindow(window)
def enter_room_from_lobby(): # 因为有title为 连连看 的隐藏窗口存在导致之前 # 无法getPixel即发送鼠标信息失败问题 # 我们需要获取visible的title为 连连看 的窗口 while True: hWnd = get_lobby_hWnd() win32gui.SetForegroundWindow(hWnd) win32gui.SetActiveWindow(hWnd) click(hWnd, "enterRoom") hWnd = win32gui.FindWindow(None, "QQ游戏 - 连连看角色版") if hWnd == 0: print("进入游戏房间失败,重新尝试进入") else: break
def check_foreground(self): try: win32gui.ShowWindow(self.hTdxMain, win32con.SW_NORMAL) win32gui.SetActiveWindow(self.hTdxMain) win32gui.SetForegroundWindow(self.hTdxMain) except: print('check_foreground except') for i in range(1, 10): if pywinauto.controls.HwndWrapper.HwndWrapper( self.hTreeLeft).IsVisible() == False: print('check_foreground') tm.sleep(0.1) else: break
def HotKeyShowWindow(Hwnd): """隐藏窗口后检测热键以显示窗口""" win32gui.ShowWindow(Hwnd, win32con.SW_HIDE) global ShowFlag ShowFlag = False while True: if ShowFlag: return if win32api.GetAsyncKeyState( win32con.VK_LCONTROL) and win32api.GetAsyncKeyState( win32con.VK_F10): win32gui.ShowWindow(Hwnd, win32con.SW_SHOW) win32gui.SetActiveWindow(Hwnd) break time.sleep(0.1)