def restore(self): # By doing normal way with EnumWindows() and then IsWindowVisible # I got about five thousand top-level windows. It sucks. # So I just walk through desktop region and to enumerate windows minx = self.d.right - self.margin - self.size; maxx = minx + self.size miny = self.margin; maxy = self.margin + self.size #print minx,miny,maxx,maxy p = POINT() step = 1; currx = minx; prev_hwnd = None wnds = set() while (currx <= maxx): curry = miny; while (curry <= maxy): p.x = currx; p.y = curry; # print currx, curry curry = curry + step hwnd = self.WindowFromPoint(p) if (hwnd in wnds): continue wnds.add(hwnd) self.InvalidateRect(hwnd, self.d, True) self.UpdateWindow(hwnd) #print p.x, p.y currx = currx + step
def get_window_at(x, y): point = POINT() point.x, point.y = x, y hwnd = ctypes.windll.user32.WindowFromPoint(point) if not hwnd: return None else: return Window(hwnd)
def get_child_window_at(self, x, y): point = POINT() point.x, point.y = x, y child_hwnd = ctypes.windll.user32.RealChildWindowFromPoint( self.__hwnd, point) if not child_hwnd: return None else: return Window(child_hwnd)
def map_to_window(x, y): '''x and y are normalized coordinates.''' width = GetSystemMetrics(SM_CXSCREEN) height = GetSystemMetrics(SM_CYSCREEN) point = POINT(2) point.x = int(x * width) point.y = int(y * height) MapWindowPoints(0, hwnd, point, 1) return point.x, point.y
def get_child_window_at(self, x, y): point = POINT() point.x, point.y = x, y child_hwnd = ctypes.windll.user32.RealChildWindowFromPoint( self.__hwnd, point ) if not child_hwnd: return None else: return Window(child_hwnd)
async def init_silent_mode(self): if self.silent_mode and not self.silent_init: point = POINT() point.x = 100 point.y = 100 ctypes.windll.user32.ClientToScreen(self.window_handle, ctypes.byref(point)) self.silent_xpos = point.x self.silent_ypos = point.y await self.walker.mouse_handler.set_mouse_position( self.silent_xpos, self.silent_ypos, convert_from_client=False) self.silent_init = True
def on_getminmaxinfo(self, hwnd, msg, wparam, lparam): if (self.min_size or self.max_size) and lparam: info = ctypes.cast(lparam, ctypes.POINTER(MINMAXINFO)).contents style = GetWindowLongW(hwnd, win32con.GWL_STYLE) dw, dh = 0, 0 if style & win32con.WS_BORDER: fw, fh = self.frame_width, self.frame_height dw = fw * 2 dh = self.caption_height + fh * 2 log( "on_getminmaxinfo window=%#x min_size=%s, max_size=%s, frame=%sx%s", hwnd, self.min_size, self.max_size, fw, fh) if self.min_size: minw, minh = self.min_size #pylint: disable=unpacking-non-sequence minw += dw minh += dh if not HOOK_MINMAXINFO_OVERRIDE: v = info.ptMinTrackSize if v: log("on_getminmaxinfo ptMinTrackSize=%ix%i", v.x, v.y) if v.x > 0: minw = max(minw, v.x) if v.y > 0: minh = max(minh, v.y) point = POINT(minw, minh) info.ptMinSize = point info.ptMinTrackSize = point log("on_getminmaxinfo actual min_size=%ix%i", minw, minh) if self.max_size: maxw, maxh = self.max_size #pylint: disable=unpacking-non-sequence maxw += dw maxh += dh if not HOOK_MINMAXINFO_OVERRIDE: for name, v in { "ptMaxSize": info.ptMaxSize, "ptMaxTrackSize": info.ptMaxTrackSize, }.items(): if v: log("on_getminmaxinfo %s=%ix%i", name, v.x, v.y) if v.x > 0: maxw = min(maxw, v.x) if v.y > 0: maxh = min(maxh, v.y) point = POINT(maxw, maxh) info.ptMaxSize = point info.ptMaxTrackSize = point log("on_getminmaxinfo actual max_size=%ix%i", maxw, maxh) return 0 log("on_getminmaxinfo%s min_size=%s, max_size=%s", (hwnd, msg, wparam, lparam), self.min_size, self.max_size) return 0
def test_collection(self): """Tests whether a collection of several rectangle and point types convert to the expected L{RectLTRB}.""" rect=RectLTRB(left=10, top=15, right=500, bottom=1000) self.assertEqual(RectLTRB.fromCollection( rect.topLeft, rect.bottomRight, rect.center, Point(15, 15), Point(20, 20), Point(50, 50), Point(400, 400), POINT(x=15, y=15), POINT(x=20, y=20), POINT(x=50, y=50), POINT(x=400, y=400), RectLTRB(left=450, top=450, right=490, bottom=990), RECT(450, 450, 490, 990) ), rect) location=RectLTWH(left=10, top=15, width=500, height=1000) self.assertEqual(RectLTWH.fromCollection( location.topLeft, location.bottomRight, location.center, Point(15, 15), Point(20, 20), Point(50, 50), Point(400, 400), POINT(x=15, y=15), POINT(x=20, y=20), POINT(x=50, y=50), POINT(x=400, y=400), RectLTRB(left=450, top=450, right=505, bottom=1010), RECT(450, 450, 490, 990) ), location)
def on_getminmaxinfo(self, hwnd, msg, wparam, lparam): info = ctypes.cast(lparam, ctypes.POINTER(MINMAXINFO)).contents el, et, er, eb = self._get_edge_sizes() if self._dialog_max_size: width = self._dialog_max_size[0] + el + er height = self._dialog_max_size[1] + et + eb point = POINT(width, height) info.ptMaxSize = point info.ptMaxTrackSize = point if self._dialog_min_size: width = self._dialog_min_size[0] + el + er height = self._dialog_min_size[1] + et + eb point = POINT(width, height) info.ptMinTrackSize = point
def mainloop(self): cursor_pos = POINT() window_rect = RECT() self_handle = self.__root.winfo_id() self_rect = RECT() timer = self.__timer @timer.add_observer def get_window(event): GetCursorPos(byref(cursor_pos)) handle = WindowFromPoint(cursor_pos) GetWindowRect(self_handle, byref(self_rect)) if not ( cursor_pos.y >= self_rect.top and \ cursor_pos.x >= self_rect.left and \ cursor_pos.y <= self_rect.bottom and \ cursor_pos.x <= self_rect.right) and \ (handle != GetParent(self_handle)): self.__sel_window = handle GetWindowRect(handle, byref(window_rect)) self.__root.geometry( f'+{max(0, window_rect.left)}+{max(0, window_rect.top)}') timer.interval = 500 timer.active = True self.__root.mainloop()
def get_window_from_point(cls, p=None, main=False): """Window From Screen Coordinates or current Mouse Position.""" if p is None: p = POINT() if not ctypes.windll.user32.GetCursorPos(byref(p)): raise ctypes.WinError() elif not isinstance(p, POINT): p = POINT(*p) w = ctypes.windll.user32.WindowFromPoint(p) w = cls(w) if main: p = w while p: w = p p = w.parent return w
def AccessibleObjectFromPoint(x, y): "Return an accessible object and an index. See MSDN for details." pacc = POINTER(IAccessible)() var = VARIANT() oledll.oleacc.AccessibleObjectFromPoint(POINT(x, y), byref(pacc), byref(var)) return pacc, var
def set_inline_position(hwnd, x, y, font_face, font_height): # borrowed from http://d.hatena.ne.jp/doloopwhile/20090627/1275176169 hIMC = windll.imm32.ImmGetContext(hwnd) status = windll.imm32.ImmGetOpenStatus(hIMC) # if not status: # Enable IME temporary. # ctypes.windll.imm32.ImmSetOpenStatus(hIMC, 1) pt = POINT(x, y) cf = COMPOSITIONFORM() cf.dwStyle = 2 # CFS_POINT cf.ptCurrentPos = pt # Supporting Weasel IME # For more detail see also WeaselIME.cpp@WeaselIME::_SetCompositionWindow cf.rcArea.left = x cf.rcArea.top = y if x == 0: cf.rcArea.left = 1 if y == 0: cf.rcArea.top = 1 cf.rcArea.right = cf.rcArea.left cf.rcArea.bottom = cf.rcArea.top windll.imm32.ImmSetCompositionWindow(hIMC, byref(cf)) lf = LOGFONT() lf.lfHeight = font_height lf.lfFaceName = font_face windll.imm32.ImmSetCompositionFontW(hIMC, byref(lf)) if not status: ctypes.windll.imm32.ImmSetOpenStatus(hIMC, 0) windll.imm32.ImmReleaseContext(hwnd, hIMC)
def get_position(self): """get mouse position""" if not self.silent_mode: point = POINT() ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return (point.x, point.y) else: return (self.silent_xpos, self.silent_ypos)
def cache_pointer_offset(self, event): #this overrides the window._get_pointer method #so we can cache the GTK position offset for synthetic wheel events gtk_x, gtk_y = event.x_root, event.y_root pos = POINT() GetCursorPos(ctypes.byref(pos)) x, y = pos.x, pos.y self.win32_pointer_offset = gtk_x - x, gtk_y - y return gtk_x, gtk_y
def action_handler(): print("mouse") global id4, proc, hwnd if proc is None: proc = subprocess.Popen(["python", "overlay.py"]) mouse = POINT() user32.GetCursorPos(ctypes.byref(mouse)) hwnd = user32.WindowFromPoint(mouse) id4 = hot.addHotkey(['mouse middle'], up, isThread=False, up=True)
def _get_pos_from_tuple(self, position: tuple): rect = self.window_rect # Adjust point to window client area point = POINT(rect.left + position[0], rect.top + position[1]) ScreenToClient(self.hwnd, byref(point)) pos = point.x | (point.y * 2**16) return pos
def drag_end(btn='left'): pt = POINT() windll.user32.GetCursorPos(byref(pt)) if btn == 'left': windll.user32.mouse_event(MOUSEEVENTF_LEFTUP, pt.x, pt.y, 0, 0) elif btn == 'right': windll.user32.mouse_event(MOUSEEVENTF_RIGHTUP, pt.x, pt.y, 0, 0) elif btn == 'middle': windll.user32.mouse_event(MOUSEEVENTF_MIDDLEUP, pt.x, pt.y, 0, 0)
def click_callback(button, pressed): menu = CreatePopupMenu() AppendMenu(menu, win32con.MF_STRING, 1024, u"Generate balloon") AppendMenu(menu, win32con.MF_STRING, 1025, u"Exit") pos = POINT() GetCursorPos(byref(pos)) hwnd = tray.hwnd user32.SetForegroundWindow(hwnd) user32.TrackPopupMenu(menu, win32con.TPM_LEFTALIGN, pos.x, pos.y, 0, hwnd, None) PostMessageA(hwnd, win32con.WM_NULL, 0, 0)
def AccessibleObjectFromPoint(x, y): """Return an accessible object and an index. See MSDN for details. @param x int global pos @param y int global pos @return dict, int """ pacc = POINTER(IAccessible)() var = VARIANT() oledll.oleacc.AccessibleObjectFromPoint(POINT(x, y), byref(pacc), byref(var)) return pacc, var
def now(normalize=DEFAULT_NORMALIZE): """Getting now coord of mouse pointer. The normalize is switch of to using mormarize coord. """ point = POINT() lppoint = ctypes.pointer(point) GetCursorPos(lppoint) if normalize: point = Normalizer.point(point) return point.x, point.y
def client_area_rect(self): client_rect = RECT() win_rect = RECT() offset = POINT() _USER32.GetClientRect(self.__hwnd, byref(client_rect)) _USER32.GetWindowRect(self.__hwnd, byref(win_rect)) _USER32.ClientToScreen(self.__hwnd, byref(offset)) x = offset.x - win_rect.left y = offset.y - win_rect.top w = client_rect.right h = client_rect.bottom return x, y, w, h
def get_cursor_position(self): """ Get cursor position. :return: A tuple of (x, y). """ # Create point structure point = POINT() # Get cursor position _GetCursorPos(byref(point)) # Return position tuple return (point.x, point.y)
def wizsdk_client_coords_to_wizwalker(self, x: int, y: int) -> tuple: """ Converts WizSDK client coords to wizwalker client coords """ # make absolute wX, wY, *_ = self.get_rect() x += wX y += wY # convert to the client coords wizwalker uses point = POINT(int(x), int(y)) if (ctypes.windll.user32.ScreenToClient(self.window_handle, ctypes.byref(point)) == 0): raise RuntimeError("Screen to client conversion failed") return (point.x, point.y)
def up(): global id4, proc, hwnd mouse = POINT() user32.GetCursorPos(ctypes.byref(mouse)) hot.removeHotkey(id=id4) if proc is not None: proc.terminate() print("-" * 40) print_handles("GetForegroundWindow", user32.GetForegroundWindow()) active_window = print_handles("WindowFromPoint", hwnd) print_handles("GetParent", user32.GetParent(active_window)) ancestor = print_handles( "GetAncestor", user32.GetAncestor(active_window, 3)) if ancestor: # GetAncestor is the most correct for our use-case, so prefer it. active_window = ancestor rect = RECT() user32.GetWindowRect(active_window, ctypes.byref(rect)) grid = find_matching_grid(mouse.x, mouse.y) if grid: grid = to_rect(grid) if is_aero_enabled(): arect = get_actual_rect(active_window) grid.left -= abs(arect.left - rect.left) grid.top -= abs(arect.top - rect.top) grid.right += abs(arect.right - rect.right) grid.bottom += abs(arect.bottom - rect.bottom) width = grid.right - grid.left height = grid.bottom - grid.top print("width: %d height: %d" % (width, height)) HWND_NOTOPMOST = -2 user32.SetWindowPos(active_window, HWND_NOTOPMOST, grid.left, grid.top, width, height, 0) user32.SetForegroundWindow(active_window) proc = None hwnd = None
def on_getminmaxinfo(self, hwnd, msg, wparam, lparam): if self.max_size and lparam: info = ctypes.cast(lparam, ctypes.POINTER(MINMAXINFO)).contents width, height = self.max_size style = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE) if style & win32con.WS_BORDER: fw, fh = self.frame_width, self.frame_height else: fw, fh = 0, 0 w = width + fw*2 h = height + self.caption_height + fh*2 point = POINT(w, h) info.ptMaxSize = point info.ptMaxTrackSize = point log("on_getminmaxinfo window=%#x max_size=%s, frame=%sx%s, minmaxinfo size=%sx%s", hwnd, self.max_size, fw, fh, w, h) return 0 log("on_getminmaxinfo window=%#x max_size=%s", hwnd, self.max_size)
def kwargsFromSuper(cls,kwargs,relation=None): UIAElement=None windowHandle=kwargs.get('windowHandle') if isinstance(relation,tuple): UIAElement=UIAHandler.handler.clientObject.ElementFromPointBuildCache(POINT(relation[0],relation[1]),UIAHandler.handler.baseCacheRequest) elif relation=="focus": try: UIAElement=UIAHandler.handler.clientObject.getFocusedElementBuildCache(UIAHandler.handler.baseCacheRequest) # This object may be in a different window, so we need to recalculate the window handle. kwargs['windowHandle']=None except COMError: log.debugWarning("getFocusedElement failed", exc_info=True) else: UIAElement=UIAHandler.handler.clientObject.ElementFromHandleBuildCache(windowHandle,UIAHandler.handler.baseCacheRequest) if not UIAElement: return False kwargs['UIAElement']=UIAElement return True
def show_popup_menu(hwnd): hide_popup_menu() menu = user32.CreatePopupMenu() user32.InsertMenuW(menu, 0, MF_BYPOSITION | MF_STRING, ID_PUBLIC, u'Get Public Key') user32.InsertMenuW(menu, 1, MF_BYPOSITION | MF_SEPARATOR, 0, None) user32.InsertMenuW(menu, 2, MF_BYPOSITION | MF_STRING, ID_EXIT, u'Exit') user32.SetMenuDefaultItem(menu, ID_PUBLIC, False) user32.SetFocus(hwnd) user32.SetForegroundWindow(hwnd) pt = POINT() user32.GetCursorPos(byref(pt)) cmd = user32.TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RETURNCMD | TPM_NONOTIFY, pt.x, pt.y, 0, hwnd, None) user32.SendMessageA(hwnd, WM_COMMAND, cmd, 0) user32.DestroyMenu(menu)
def set_inline_position(hwnd, x, y, font_face, font_height): # borrowed from http://d.hatena.ne.jp/doloopwhile/20090627/1275176169 hIMC = windll.imm32.ImmGetContext(hwnd) status = windll.imm32.ImmGetOpenStatus(hIMC) if not status: windll.imm32.ImmReleaseContext(hwnd, hIMC) return pt = POINT(x, y) cf = COMPOSITIONFORM() cf.dwStyle = 2 # CFS_POINT cf.ptCurrentPos = pt windll.imm32.ImmSetCompositionWindow(hIMC, byref(cf)) lf = LOGFONT() lf.lfHeight = font_height lf.lfFaceName = font_face windll.imm32.ImmSetCompositionFontW(hIMC, byref(lf)) windll.imm32.ImmReleaseContext(hwnd, hIMC)
def click_callback(button, pressed): CreatePopupMenu = user32.CreatePopupMenu CreatePopupMenu.restype = ctypes.wintypes.HMENU CreatePopupMenu.argtypes = [] AppendMenu = user32.AppendMenuW AppendMenu.restype = ctypes.wintypes.BOOL AppendMenu.argtypes = [ ctypes.wintypes.HMENU, ctypes.wintypes.UINT, ctypes.wintypes.UINT, ctypes.wintypes.LPCWSTR ] menu = CreatePopupMenu() AppendMenu(menu, win32con.MF_STRING, 1024, u"Generate balloon") AppendMenu(menu, win32con.MF_STRING, 1025, u"Exit") pos = POINT() GetCursorPos(byref(pos)) hwnd = tray.hwnd user32.SetForegroundWindow(hwnd) user32.TrackPopupMenu(menu, win32con.TPM_LEFTALIGN, pos.x, pos.y, 0, hwnd, None) PostMessageA(hwnd, win32con.WM_NULL, 0, 0)
def getCoordinate(self, whos): pyautogui.FAILSAFE = False try: QMessageBox.about(None, "提示!!!", "放到鼠标点击位置2秒钟") self.mainwind.hide() time.sleep(2) po = POINT() windll.user32.GetCursorPos(byref(po)) if whos == 1: self.y1 = int(po.y) self.x1 = int(po.x) self.click.lineEdit_2.setText( str(self.x1) + ":" + str(self.y1)) elif whos == 2: self.y2 = int(po.y) self.x2 = int(po.x) self.click.lineEdit_6.setText( str(self.x2) + ":" + str(self.y2)) except KeyboardInterrupt as e: print('有异常请确定' + e) self.mainwind.show()
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)
def makePOINT(point): pt = POINT() pt.x, pt.y = point return pt