def tearDown(self): for hndle in self.tempFileHndles: if not win32gui.IsWindow(hndle): print("???window does not exist: %s"% hndle) continue if hndle == self.thisHndle: # print('window hndle %s may not match "thisHndle": %s'% (hndle, self.thisHndle)) continue # print('close window with hndle: %s'% hndle) natlinkutilsqh.SetForegroundWindow(hndle) curHndle = natlinkutilsqh.GetForegroundWindow() if hndle == curHndle: if hndle in self.killActions: # natlinkutilsqh.SetForegroundWindow(self.thisHndle) # place to break in debug mode # natlinkutilsqh.SetForegroundWindow(curHndle) action(self.killActions[hndle], modInfo=self.modInfos[hndle]) else: natlinkutils.playString("{alt+f4}") natlinkutilsqh.SetForegroundWindow(self.thisHndle) self.disconnect() # disabled, natConnect notClosedHndles = [] for hndle in self.tempFileHndles: if hndle and win32gui.IsWindow(hndle): notClosedHndles.append(hndle) if self.frescHndle: if self.frescHndle in notClosedHndles: notClosedHndles.remove(self.frescHndle) else: raise TestError('Fresobaldi should not be closed after the test') if notClosedHndles: raise TestError('Hndles not close, but should: %s'% notClosedHndles)
def __init__(self, hwnd): self.handle = hwnd self.last_window_pos = win32gui.GetWindowRect(self.handle) self.last_received_pos = self.last_window_pos self.rect = Rect(self.last_window_pos) self.floating_rect = self.rect.copy() self.last_set_rect = self.rect.copy() self.window_class = win32gui.GetClassName(hwnd) self.window_title = win32gui.GetWindowText(hwnd) self.space = None self.closed = False self.focused = False self.hidden = False self.becoming_visible = False self.floating = False self.can_tile = True self.take_new_rect = False self.force_closed = False self.always_top = False self.force_always_top = False self.force_borders = None self.minimized = False self.is_dropdown = False parent_handle = win32api.GetWindowLong(self.handle, win32con.GWL_HWNDPARENT) self.is_child_window = win32gui.IsWindow(parent_handle) self.dragging = False self.drag_ticks_with_movement = 0 self.drag_ticks_since_start = 0 self.drag_ticks_since_last_movement = 0 self.drop_space = None self.drop_slot = None self.drop_ticks_inside_slot = 0
def gain_GPS_handle(self): MDIClient_handle = self.get_handle('MDIClient') # todo 这里会有角标越界的bug view_path_name = str(self.radar_view_name).split(" - ")[1] hwndChildList = [] handle = None win32gui.EnumChildWindows(MDIClient_handle, lambda hwnd, param: param.append(hwnd), hwndChildList) for hwnd in hwndChildList: if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd): window_name = win32gui.GetWindowText(hwnd) if window_name and str(view_path_name).find(window_name) >= 0: handle = hwnd break AfxMDIFrame42s_1 = win32gui.FindWindowEx(handle, None, 'AfxMDIFrame42s', None) AfxMDIFrame42s_2 = win32gui.FindWindowEx(AfxMDIFrame42s_1, None, 'AfxMDIFrame42s', None) AfxFrameOrView42 = win32gui.FindWindowEx(AfxMDIFrame42s_2, None, 'AfxFrameOrView42s', None) # win32gui.EnumChildWindows(handle, lambda hwnd, param: param.append(hwnd), hwndChildList) # for hwnd in hwndChildList: # if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWi ndowVisible(hwnd): # window_name = win32gui.GetClassName(hwnd) # if window_name and str(window_name).find('AfxFrameOrView42s') >= 0: # AfxFrameOrView42 = hwnd path = self.win.window_capture('GPS.bmp', AfxFrameOrView42) self.get_gps(path) msctls_statusbar32 = win32gui.FindWindowEx(self.radar_view_handle, None, 'msctls_statusbar32', None) path = self.win.window_capture('H.bmp', msctls_statusbar32) self.get_deepness(path)
def main(): kc = KakaoChatter('김영후', r'김영후') #kc = KakaoChatter('뉴비', r'카카오톡 봇 만들기 방&카카오톡 봇 질문방') #kc = KakaoChatter('강인공지능', r'Abstract') cog = 'ㄸ' startmsg = f'앵무새봇 시작. {cog}뒤에 오는 문장을 따라합니다. {cog}종료를 입력하면 종료합니다.' endmsg = f'{cog}종료' readcycle = 0.5 kc.sendText(startmsg) goodend = False while wg.IsWindow(kc.hwndMain) and (not goodend): newchat = kc.readNewchat() for nc in newchat.chatlist: if nc.text == endmsg: goodend = True break if len(nc.text) > len(cog) and nc.text[:len(cog)] == 'ㄸ': kc.sendText(nc.text[len(cog):]) time.sleep(0.2) time.sleep(readcycle) if goodend: kc.sendText('앵무새봇이 정상적으로 종료되었습니다.') else: print('앵무새봇이 강제 종료되었습니다.')
def callback(hwnd, mouse): if win32gui.IsWindow(hwnd): title = win32gui.GetWindowText(hwnd) title = title.decode(u'gb2312') for word in [u'12306分流抢票']: if word in title: handlerList.append((hwnd, title))
def getAllActiveWindow(hwnd, mouse): # 去掉下面这句就所有都输出了,但是我不需要那么多 if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): titles.add( win32gui.GetWindowText(hwnd) + " " + win32gui.GetClassName(hwnd))
def wait(self, timeout=60): '''等待消息同步 ''' if self._syncwnd == 0: return win32event.ResetEvent(self._eventobj) try: win32gui.PostMessage(self._syncwnd, win32con.WM_TIMER, 0, 0) except pywintypes.error as e: if e.winerror == winerror.ERROR_INVALID_WINDOW_HANDLE: return raise e start_time = time.time() end_time = start_time while end_time - start_time <= timeout: if win32gui.IsWindow(self._syncwnd): ret = win32event.WaitForSingleObject(self._eventobj, 500) if ret == win32con.WAIT_OBJECT_0: break else: end_time = time.time() else: win32api.CloseHandle(self._eventobj) del MsgSyncer.pid_event_map[self._pid] break if end_time - start_time > timeout: raise RuntimeError('消息同步超时(%d秒)'%timeout)
def IsAlive(self): """ Checks to make sure the window is still open :return: True if window is still open else False :rtype: bool """ return bool(win32gui.IsWindow(self.hwnd))
def _window_enum_callback(self, hwnd, regex): '''Pass to win32gui.EnumWindows() to check all open windows''' if self._hwnd is None and re.match( regex, str(win32gui.GetWindowText(hwnd))) is not None: if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): l_hwnd.append(hwnd)
def check_needs_reset(self): if self.hwnd: if not win32gui.IsWindow(self.hwnd): logger.warning(f"HWND became invalid - resetting") return True style = win32api.GetWindowLong(self.hwnd, GWL_STYLE) if style != self.style: logger.warning(f"GWL_STYLE changed - resetting") return True ex_style = win32api.GetWindowLong(self.hwnd, GWL_EXSTYLE) if ex_style != self.ex_style: logger.warning(f"GWL_EXSTYLE changed - resetting") return True win_rect = win32gui.GetWindowRect(self.hwnd) if win_rect != self.win_rect: logger.warning(f"WindowRect changed - resetting") return True client_rect = win32gui.GetClientRect(self.hwnd) if client_rect != self.client_rect: logger.warning(f"ClientRect changed - resetting") return True if self.foreground: monitor = _get_monitor_containing(self.win_rect.center, self.monitors) if not monitor or self.monitor != monitor: logger.warning( f"Monitor containing center changed - resetting") return True return False
def find(hwnd, nouse): title = win32gui.GetWindowText(hwnd) if name in title and \ win32gui.IsWindow(hwnd) and \ win32gui.IsWindowEnabled(hwnd) and \ win32gui.IsWindowVisible(hwnd): result[hwnd] = title
def winEnumHandler(hwnd, ctx): if win32gui.IsWindow(hwnd) and win32gui.IsWindowVisible( hwnd) and win32gui.IsWindowEnabled(hwnd): print 'HEX', hex(hwnd), 'Text:', win32gui.GetWindowText(hwnd) if 'Administrator' in win32gui.GetWindowText(hwnd): print 'try to setfore' # win32gui.SetActiveWindow(hwnd) # win32gui.BringWindowToTop(hwnd) # win32gui.SetFocus(hwnd) # win32gui.SetForegroundWindow(hwnd) # win32gui.ShowWindow(hwnd,win32con.SW_SHOWDEFAULT) # win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_F1, 0) # win32api.PostMess2age(hwnd, win32con.WM_KEYUP, win32con.VK_F1, 0) # win32api.PostMessage(hwnd, win32con.WM_SETTEXT, None, 'win32con.VK_F1') # win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_TAB, 0) # win32api.keybd_event(86,0,0,0)221 # win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0) # SendMessage(hwnd, 258, ord('a'), 0) # win32api.keybd_event(112,0,0,0)2 # win32api.keybd_event(112,0,win32con.KEYEVENTF_KEYUP,0) # win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) # time.sleep(1) # win32api.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0) # win32api.keybd_event(127,0,0,0) # win32api.keybd_event(86,0,0,0) # win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0) # win32api.keybd_event(17,0,win32con.KEYEVE2NTF_KEYUP,0) win32api.keybd_event(50, 0, 0, 0)
def poll_window(path, app_name, timeout=30): class Checker: def __init__(self, filename, app_name): self.filename = filename self.root_filename = os.path.splitext(filename)[0] self.app_name = app_name self.hwnd = None def enum_window_proc(hwnd, checker): text = win32gui.GetWindowText(hwnd) if (checker.filename in text or checker.root_filename in text and checker.app_name in text): checker.hwnd = hwnd return False return True checker = Checker(os.path.basename(path), app_name) start_time = time.time() while True: try: win32gui.EnumWindows(enum_window_proc, checker) except pywintypes.error as e: if e.funcname != "EnumWindows" or e.winerror not in [0, 1400]: raise if checker.hwnd: break if time.time() - start_time > timeout: raise TimeoutError("couldn't find a window for {!r}".format( checker.filename)) time.sleep(0.1) while win32gui.IsWindow(checker.hwnd): time.sleep(0.5)
def get_all_hwnd(hwnd, mouse): ''' 获取所有阴阳师窗口 ''' if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd): if win32gui.GetWindowText(hwnd) == u'阴阳师-网易游戏': hwndlist.append(hwnd)
def __mpcReadyInSlaveMode(self): while True: time.sleep(10) if not win32gui.IsWindow(self.__listener.mpcHandle): if self.callbacks.onMpcClosed: self.callbacks.onMpcClosed(None) break
def pyqtCaptureImgeSave(hwnd: int = 0, imagePath: str = None, imageName: str = None): """ pyqt5窗口截图保存方法,支持后台截图方式,窗口不能最小化. :param hwnd: 窗口句柄,0代表整个屏幕 :param imgePath: bmp图片路径 :param imageName: bmp图片文件名 :return: 图片路径字符串 """ # 窗口句柄校验 if hwnd != 0 and not win32gui.IsWindow(hwnd): raise Exception(str(hwnd) + "无效的窗口句柄。") # 图片路径校验,不存在则新建 if imagePath is None: imagePath = "./" else: if not os.path.exists(imagePath): os.mkdir(imagePath) # 图片文件名校验,不存在则生成随机名 if imageName is None: imageName = genRandomFileName("pyqt", "bmp") else: if not imageName.lower().endswith(".bmp"): raise Exception("文件扩展名无效,只支持bmp格式扩展名") # 图片完整路径拼接 imageURI = getFileAbsPath(imagePath + imageName) logtrace.logOut(imageURI) pyqtCaptureImge(hwnd).save(imageURI) return imageURI
def is_app_window(win): # Determine if the window is application window if not win32gui.IsWindow(win): return False # Invisible windows are of no interest if not win32gui.IsWindowVisible(win): return False # Also disabled windows we do not want if not win32gui.IsWindowEnabled(win): return False exstyle = win32gui.GetWindowLong(win, win32con.GWL_EXSTYLE) # AppWindow flag would be good at this point if exstyle & win32con.WS_EX_APPWINDOW != win32con.WS_EX_APPWINDOW: style = win32gui.GetWindowLong(win, win32con.GWL_STYLE) # Child window is suspicious if style & win32con.WS_CHILD == win32con.WS_CHILD: return False parent = win32gui.GetParent(win) owner = win32gui.GetWindow(win, win32con.GW_OWNER) # Also window which has parent or owner is probably not an application window if parent > 0 or owner > 0: return False # Tool windows we also avoid # TODO: Avoid tool windows? Make exceptions? Make configurable? if exstyle & win32con.WS_EX_TOOLWINDOW == win32con.WS_EX_TOOLWINDOW: return False # There are some specific windows we do not want to switch to win_class = win32gui.GetClassName(win) if "WindowsScreensaverClass" == win_class or "tooltips_class32" == win_class: return False # Now we probably have application window return True
def get_win_type(hwnd): # TODO: Improve the conditions # Note: No DOCK type # Is default ignore window? if _default_ignore_wins.check(hwnd): return WindowType.OTHER # Is an invalid window? if not win32gui.IsWindow(hwnd) or not win32gui.IsWindowEnabled(hwnd) or \ not win32gui.GetWindowText(hwnd): return WindowType.OTHER # Is specific class? class_name = win32gui.GetClassName(hwnd) if class_name == '#32770': # Dialog return WindowType.DIALOG # Is non-application window? if win32gui.GetParent(hwnd): return WindowType.OTHER # Is Floating or non-resizable? style = win32gui.GetWindowLong(hwnd, win32con.GWL_STYLE) ex_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) if not style & win32con.WS_SIZEBOX or \ ex_style & win32con.WS_EX_TOOLWINDOW or \ ex_style & win32con.WS_EX_TOPMOST: return WindowType.DIALOG else: return WindowType.NORMAL
def EnumWindowsProc(hwnd, mouse): # show all the window msg if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible( hwnd) and win32gui.GetWindowText(hwnd) != "": text = win32gui.GetWindowText(hwnd) classname = win32gui.GetClassName(hwnd) titles.append({'win_name': text, 'hwnd': hwnd, 'classname': classname})
def is_closed(self): '''是否已关闭 ''' if sys.platform == 'win32': import win32gui return not win32gui.IsWindow(self._handle) else: raise NotImplementedError
def add_win_name(self, hwnd, extra): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): win_name = win32gui.GetWindowText(hwnd).decode('GB2312') if len(win_name) == 0: return self.com_win_name_list.addItem(win_name)
def callback(found_win, windows): # Determine if the window is application window if not win32gui.IsWindow(found_win): return True # Invisible windows are of no interest if not win32gui.IsWindowVisible(found_win): return True # Also disabled windows we do not want if not win32gui.IsWindowEnabled(found_win): return True exstyle = win32gui.GetWindowLong(found_win, win32con.GWL_EXSTYLE) # AppWindow flag would be good at this point if exstyle & win32con.WS_EX_APPWINDOW != win32con.WS_EX_APPWINDOW: style = win32gui.GetWindowLong(found_win, win32con.GWL_STYLE) # Child window is suspicious if style & win32con.WS_CHILD == win32con.WS_CHILD: return True parent = win32gui.GetParent(found_win) owner = win32gui.GetWindow(found_win, win32con.GW_OWNER) # Also window which has parent or owner is probably not an application window if parent > 0 or owner > 0: return True # Tool windows we also avoid # TODO: Avoid tool windows? Make exceptions? Make configurable? if exstyle & win32con.WS_EX_TOOLWINDOW == win32con.WS_EX_TOOLWINDOW: return True # There are some specific windows we do not want to switch to win_class = win32gui.GetClassName(found_win) if "WindowsScreensaverClass" == win_class or "tooltips_class32" == win_class: return True # Now we probably have application window # Get title # Using own GetWindowText, because win32gui.GetWindowText() doesn't # return unicode string. win_title = GetWindowText(found_win) # Removing all accents from characters win_title = unicodedata.normalize( 'NFKD', win_title) #.encode('ascii', 'ignore') # Get PID so we can get process name _, process_id = win32process.GetWindowThreadProcessId(found_win) process = "" try: # Get process name phandle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, process_id) pexe = win32process.GetModuleFileNameEx(phandle, 0) pexe = os.path.normcase(os.path.normpath(pexe)) # Remove extension process, _ = os.path.splitext(os.path.basename(pexe)) except Exception as e: pass # Add hwnd and title to the list windows.append((found_win, "%s: %s" % (process, win_title))) return True
def wait_for_wnd_closed_h(h, timeout=10): duration = 0 step = 0.5 while win32gui.IsWindow(h): sleep(step) duration += step if duration >= timeout: raise Exception( "waiting for window handle '{}' closed timeout".format(h))
def get_all_hwnd(hwnd_id): """ 获取所有的窗体的id,回调函数 :param hwnd_id: 窗体id """ if win32gui.IsWindow(hwnd_id) and win32gui.IsWindowEnabled( hwnd_id) and win32gui.IsWindowVisible(hwnd_id): hwnd_title.update({win32gui.GetWindowText(hwnd_id): hwnd_id})
def __init__(self, hintkeys, hotkeys): super(HintWindowMode, self).__init__(hotkeys) self.hintkeys = hintkeys self.item_list = [] self.overlay_global() self.bg_color = (0, 0, 0) self.hint_color = (255, 255, 0) self.border_color = (0, 128, 255) self.title_color = (128, 128, 128) self.floating_border = (255, 0, 255) self.border_width = 1 self.box_size = (200, 50) self.selection_text = "" self.max_hidden_row = 10 self.closed = False self.dirty = True hidden_windows = {} for hwnd, window in pylewm.windows.Windows.items(): if win32gui.IsWindow(hwnd): if window.is_dropdown: continue if window.minimized: continue if window.space and not window.space.visible: if window.space.monitor not in hidden_windows: hidden_windows[window.space.monitor] = [] hidden_windows[window.space.monitor].append(window) continue item = WindowItem() item.window = window item.rect = window.rect item.is_hidden = False self.item_list.append(item) for monitor, window_list in hidden_windows.items(): show_count = len(window_list) item_width = monitor.rect.width / min(self.max_hidden_row, show_count) for i in range(0, show_count): window = window_list[i] item = WindowItem() item.window = window item.title = win32gui.GetWindowText(window.handle) item.rect = Rect.from_pos_size( (monitor.rect.left + (i % self.max_hidden_row) * item_width, monitor.rect.bottom - 30 * (int(i / self.max_hidden_row) + 1)), (item_width, 30)) item.is_hidden = True self.item_list.append(item) pylewm.modes.hint_helpers.create_hints(self.item_list, self.hintkeys)
def is_window(hwnd): """ @param hwnd HWND @return unicode or "" """ try: return bool(win32gui.IsWindow(hwnd)) except: return False
def run(self): readcycle = 0.5 goodend = False while wg.IsWindow(kc.hwndMain) and (not goodend): newchat = kc.readNewchat() for nc in newchat.chatlist: goodend = reply(nc) time.sleep(readcycle)
def get_all_hwnd(hwnd, mouse): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): print "************************" info = u'title: ' + win32gui.GetWindowText(hwnd).decode( "gbk") + u' 类名: ' + win32gui.GetClassName(hwnd) hwnd_title.update({hwnd: info}) if win32gui.GetWindowText(hwnd).decode("gbk") == u'胡强力': active_window(hwnd)
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 is not "": print(h, t)
def get_all_window(hwnd, mouse): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and \ win32gui.IsWindowVisible(hwnd): titles.add(win32gui.GetWindowText(hwnd)) if win32gui.GetWindowText(hwnd) == "查找": search.add(hwnd) if "添加好友" in win32gui.GetWindowText(hwnd): add_friends.append([hwnd, win32gui.GetWindowRect(hwnd)]) print('CurrentHwnd', hwnd)