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 pointer_grab(window, *args): hwnd = get_window_handle(window) grablog("pointer_grab%s window=%s, hwnd=%s", args, window, hwnd) if not hwnd: window._client.pointer_grabbed = None return wrect = RECT() GetWindowRect(hwnd, byref(wrect)) grablog("GetWindowRect(%i)=%s", hwnd, wrect) if DwmGetWindowAttribute: # Vista & 7 stuff rect = RECT() DWMWA_EXTENDED_FRAME_BOUNDS = 9 DwmGetWindowAttribute(HWND(hwnd), DWORD(DWMWA_EXTENDED_FRAME_BOUNDS), byref(rect), sizeof(rect)) #wx1,wy1,wx2,wy2 = rect.left, rect.top, rect.right, rect.bottom grablog("DwmGetWindowAttribute: DWMWA_EXTENDED_FRAME_BOUNDS(%i)=%s", hwnd, (rect.left, rect.top, rect.right, rect.bottom)) bx = GetSystemMetrics(win32con.SM_CXSIZEFRAME) by = GetSystemMetrics(win32con.SM_CYSIZEFRAME) top = by style = GetWindowLongW(hwnd, win32con.GWL_STYLE) if style & win32con.WS_CAPTION: top += GetSystemMetrics(win32con.SM_CYCAPTION) grablog(" window style=%s, SIZEFRAME=%s, top=%i", style_str(style), (bx, by), top) coords = wrect.left + bx, wrect.top + top, wrect.right - bx, wrect.bottom - by clip = RECT(*coords) r = ClipCursor(clip) grablog("ClipCursor%s=%s", coords, r) window._client.pointer_grabbed = window._id
def _getCaretOffset(self): caretRect=getCaretRect(self.obj) objLocation=self.obj.location objRect=RECT(objLocation[0],objLocation[1],objLocation[0]+objLocation[2],objLocation[1]+objLocation[3]) objRect.left,objRect.top=windowUtils.physicalToLogicalPoint( self.obj.windowHandle,objRect.left,objRect.top) objRect.right,objRect.bottom=windowUtils.physicalToLogicalPoint( self.obj.windowHandle,objRect.right,objRect.bottom) caretRect.left=max(objRect.left,caretRect.left) caretRect.top=max(objRect.top,caretRect.top) caretRect.right=min(objRect.right,caretRect.right) caretRect.bottom=min(objRect.bottom,caretRect.bottom) # Find a character offset where the caret overlaps vertically, overlaps horizontally, overlaps the baseline and is totally within or on the correct side for the reading order try: return self._findCaretOffsetFromLocation(caretRect,validateBaseline=True,validateDirection=True) except LookupError: pass # Find a character offset where the caret overlaps vertically, overlaps horizontally, overlaps the baseline, but does not care about reading order (probably whitespace at beginning or end of a line) try: return self._findCaretOffsetFromLocation(caretRect,validateBaseline=True,validateDirection=False) except LookupError: pass # Find a character offset where the caret overlaps vertically, overlaps horizontally, but does not care about baseline or reading order (probably vertical whitespace -- blank lines) try: return self._findCaretOffsetFromLocation(caretRect,validateBaseline=False,validateDirection=False) except LookupError: raise RuntimeError
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_rect(self, normalize=True): rect = RECT() lprect = ctypes.pointer(rect) GetWindowRect(self.hwnd, lprect) if normalize: rect.left = Normalizer.xx(rect.left) rect.right = Normalizer.xx(rect.right) rect.top = Normalizer.yy(rect.top) rect.bottom = Normalizer.yy(rect.bottom) return rect
def OnSizing(self, hWnd, msg, wParam, lParam): """ Intercepts moving events at the Win32 level For special case sizing rules while docked """ #log.debug('OnSizing') # WM_SIZING callback if not (self.Enabled and self.docked): #log.debug('Not docked') return try: if self.__sizing: return except AttributeError: pass side = self.side if not self.bypassSizeEvents and ((side == ABE_LEFT and wParam == WMSZ_RIGHT) or (side == ABE_RIGHT and wParam == WMSZ_LEFT)): # lParam is a pointer to a RECT log.debug('Docked sizing') r = wx.Rect.FromRECT(RECT.from_address(lParam)) #@UndefinedVariable # readjust the docking rectangle self.__sizing = True # this will cause the window to resize self.dockedRect = r # also save the width in our "oldSize" which is used when the window is finally undocked self.oldSize.width = r.width self.__sizing = False else: log.debug('Resize restricted') d = self.dockedRect # lParam holds the address of the RECT which will be the new # window size. setting it to our docked rectangle is like # "cancelling" the resize r = RECT.from_address(lParam) #@UndefinedVariable # set these explicitly so they go into memory at lParam. r.x = d.x r.y = d.y r.right = d.x + d.width r.bottom = d.y + d.height return False
def getImageFromSource(self, current_source): if current_source == "clipboardImage": recognizeImage = self.getImageFromClipboard() imageInfo = RecogImageInfo(0, 0, recognizeImage.width, recognizeImage.height, 1) return imageInfo, recognizeImage elif current_source == "clipboardURL": return None elif current_source == "foreGroundWindow": foregroundWindow = winUser.getForegroundWindow() desktopWindow = winUser.getDesktopWindow() foregroundRect = RECT() desktopRect = RECT() winUser.user32.GetWindowRect(foregroundWindow, byref(foregroundRect)) winUser.user32.GetWindowRect(desktopWindow, byref(desktopRect)) left = max(foregroundRect.left, desktopRect.left) right = min(foregroundRect.right, desktopRect.right) top = max(foregroundRect.top, desktopRect.top) bottom = min(foregroundRect.bottom, desktopRect.bottom) if right <= left or bottom <= top: ui.message(_("Current window position is invalid.")) return from locationHelper import RectLTRB windowRectLTRB = RectLTRB( left=left, right=right, top=top, bottom=bottom ) imageInfo = RecogImageInfo( windowRectLTRB.left, windowRectLTRB.top, windowRectLTRB.width, windowRectLTRB.height, 1 ) recognizeImage = ImageGrab.grab(( windowRectLTRB.top, windowRectLTRB.left, windowRectLTRB.width, windowRectLTRB.height )) return imageInfo, recognizeImage elif current_source == "wholeDesktop": recognizeImage = ImageGrab.grab() imageInfo = RecogImageInfo(0, 0, recognizeImage.width, recognizeImage.height, 1) return imageInfo, recognizeImage else: # Translators: Reported when source is not correct. ui.message(_("Unknown source: %s" % current_source)) return None
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 GetHeight(self): dc = ctypes.windll.User32.GetDC(self.hwnd) r = RECT() #ctypes.windll.User32.GetWindowRect(self.hwnd, byref(r)) ctypes.windll.User32.GetClientRect(self.hwnd, byref(r)) ctypes.windll.User32.ReleaseDC(self.hwnd, dc) return r.bottom-r.top
def GetWidth(self): dc = ctypes.windll.User32.GetDC(self.hwnd) r = RECT() #ctypes.windll.User32.GetWindowRect(self.hwnd, byref(r)) ctypes.windll.User32.GetClientRect(self.hwnd, byref(r)) ctypes.windll.User32.ReleaseDC(self.hwnd, dc) return r.right-r.left
def rect(self): """Window Rectangle.""" r = RECT(0, 0, 0, 0) p = byref(r) if not ctypes.windll.user32.GetWindowRect(self.hwnd, p): raise ctypes.WinError() return Rect(r.left, r.top, r.right - r.left, r.bottom - r.top)
def enum_windows_cb(hwnd, lparam): if not IsWindowVisible(hwnd): log("window %#x is not visible", hwnd) return True pid = c_ulong() thread_id = GetWindowThreadProcessId(hwnd, byref(pid)) if pid==ourpid: log("skipped our own window %#x, thread id=%#x", hwnd, thread_id) return True rect = RECT() if GetWindowRect(hwnd, byref(rect))==0: log("GetWindowRect failure") return True if hwnd==taskbar: log("skipped taskbar") return True #skipping IsWindowEnabled check length = GetWindowTextLengthW(hwnd) buf = create_unicode_buffer(length+1) if GetWindowTextW(hwnd, buf, length+1)>0: window_title = buf.value else: window_title = '' left, top, right, bottom = rect.left, rect.top, rect.right, rect.bottom w = right-left h = bottom-top if left<=-32000 or top<=-32000: log("%r is not visible: %s", window_title, (left, top, w, h)) if w<=0 and h<=0: log("skipped invalid window size: %ix%i", w, h) return True windows[hwnd] = (window_title, (left, top, w, h)) return True
def DrawThemeTextEx(win, handle, text): # Draw the text dto = DTTOPTS() uFormat = DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX dto.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE dto.iGlowSize = 10 rcText2 = RECT(0,0,150,30) #rcText2 -= rcText2.TopLeft() # same rect but with (0,0) as the top-left #HRESULT DrawThemeTextEx( # HTHEME hTheme, # HDC hdc, # int iPartId, # int iStateId, # LPCWSTR pszText, # int iCharCount, # DWORD dwFlags, # LPRECT pRect, # const DTTOPTS *pOptions #); ux.DrawThemeTextEx ( win._hTheme, handle, 0, 0, unicode(text), -1, uFormat, byref(rcText2), byref(dto) );
def getNoesisWindowRect(): hNoesisWnd = noesis.getWindowHandle() if hNoesisWnd: rect = RECT() if user32.GetWindowRect(hNoesisWnd, byref(rect)): return (rect.left, rect.top, rect.right, rect.bottom) return None
def _getCaretOffset(self): caretRect = winUser.getGUIThreadInfo(self.obj.windowThreadID).rcCaret objLocation = self.obj.location objRect = RECT(objLocation[0], objLocation[1], objLocation[0] + objLocation[2], objLocation[1] + objLocation[3]) tempPoint = winUser.POINT() tempPoint.x = caretRect.left tempPoint.y = caretRect.top winUser.user32.ClientToScreen(self.obj.windowHandle, byref(tempPoint)) caretRect.left = max(objRect.left, tempPoint.x) caretRect.top = max(objRect.top, tempPoint.y) tempPoint.x = caretRect.right tempPoint.y = caretRect.bottom winUser.user32.ClientToScreen(self.obj.windowHandle, byref(tempPoint)) caretRect.right = min(objRect.right, tempPoint.x) caretRect.bottom = min(objRect.bottom, tempPoint.y) for charOffset, (charLeft, charTop, charRight, charBottom, charBaseline) in enumerate(self._textAndRects[1]): #Real text with a character baseline #The caret must be anywhere before the horizontal center of the character and the bottom of the caret must touch or go through the character baseline if charBaseline >= 0 and caretRect.left < ( (charLeft + charRight) / 2) and caretRect.top < charBaseline <= caretRect.bottom: return charOffset for charOffset, (charLeft, charTop, charRight, charBottom, charBaseline) in enumerate(self._textAndRects[1]): #vertical whitespace (possible blank lines) #The caret must be fully contained in the whitespace to match if charBaseline == -1 and caretRect.left >= charLeft and caretRect.right <= charRight and not ( caretRect.bottom <= charTop or charBottom <= caretRect.top): return charOffset raise RuntimeError
def test_ctypesRECT(self): # Intersection self.assertEqual( RectLTRB(left=2, top=2, right=4, bottom=4).intersection( RECT(left=3, top=3, right=5, bottom=5)), RectLTRB(left=3, top=3, right=4, bottom=4)) # Superset self.assertTrue( RectLTRB(left=2, top=2, right=6, bottom=6).isSuperset( RECT(left=2, top=2, right=4, bottom=4))) # Subset self.assertTrue( RectLTRB(left=2, top=2, right=4, bottom=4).isSubset(RECT(left=2, top=2, right=6, bottom=6))) # in self.assertIn(RECT(left=2, top=2, right=4, bottom=4), RectLTRB(left=2, top=2, right=6, bottom=6)) self.assertNotIn(RECT(left=2, top=2, right=4, bottom=4), RectLTRB(left=2, top=2, right=4, bottom=4)) # Equality self.assertEqual(RECT(left=2, top=2, right=4, bottom=4), RectLTRB(left=2, top=2, right=4, bottom=4)) self.assertNotEqual(RECT(left=2, top=2, right=4, bottom=4), RectLTRB(left=2, top=2, right=6, bottom=6))
def getCaretRect(obj): left=c_long() top=c_long() right=c_long() bottom=c_long() res=watchdog.cancellableExecute(NVDAHelper.localLib.displayModel_getCaretRect, obj.appModule.helperLocalBindingHandle, obj.windowThreadID, byref(left),byref(top),byref(right),byref(bottom)) if res!=0: raise RuntimeError("displayModel_getCaretRect failed with res %d"%res) return RECT(left,top,right,bottom)
def _rect(self): rect = RECT() _USER32.GetWindowRect(self.__hwnd, byref(rect)) return ( rect.left, rect.top, (rect.right - rect.left), (rect.bottom - rect.top), )
def window_rect(self) -> RECT: """Returns a rect with from the registered window. Returns: RECT: [rect.left, rect.top, rect.right, rect.bottom] """ rect = RECT() GetWindowRect(self.hwnd, byref(rect)) return rect
def take_current_ss(): global global_offsetx, global_offsety, app_center, bluestacks fname = os.path.join(MEDIA_BASE, 'current.jpg') rect = RECT() ctypes.windll.user32.GetWindowRect(bluestacks, ctypes.byref(rect)) global_offsetx = rect.left global_offsety = rect.top app_center = ((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2) ImageGrab.grab(bbox=(rect.left, rect.top, rect.right, rect.bottom)).save(fname, 'jpeg') return fname
def load_presentation(self): """ Called when a presentation is added to the SlideController. It builds the environment, starts communication with the background PptView task started earlier. """ log.debug(u'LoadPresentation') renderer = self.controller.plugin.renderer rect = renderer.screens.current[u'size'] rect = RECT(rect.x(), rect.y(), rect.right(), rect.bottom()) filepath = str(self.filepath.replace(u'/', u'\\')) if not os.path.isdir(self.get_temp_folder()): os.makedirs(self.get_temp_folder()) self.pptid = self.controller.process.OpenPPT(filepath, None, rect, str(self.get_temp_folder()) + '\\slide') if self.pptid >= 0: self.create_thumbnails() self.stop_presentation() return True else: return False
def _set_weapon_slot_pos(self): """Set the weapon slot position in the game's window.""" game_window_rect = RECT() ctypes.windll.user32.GetWindowRect(self.game_window, ctypes.byref(game_window_rect)) self.weapon_slot_pos = { 'top': game_window_rect.top + self.weapon_slot_top, 'left': game_window_rect.left + self.weapon_slot_left, 'width': self.weapon_slot_width, 'height': self.weapon_slot_height }
def to_wintypes(self): rect = RECT() rect.left = self.left rect.top = self.top rect.right = self.right rect.bottom = self.bottom return rect
def render(text, image_width, image_height): """ Render stamp text as bitmap using Windows GDI32 API, return pixels and actual stamp image size """ with Win32GdiFont(FONT_NAME) as font_header: with Win32GdiDeviceContext(font_header) as device_context: # compute text size text_size = SIZE() assert windll.gdi32.GetTextExtentPoint32W( device_context, text, len(text), ctypes.byref(text_size)) # add some margins width = text_size.cx + 6 height = text_size.cy + 6 buffer_length = width * height * 4 # clip by image size if width > image_width: width = image_width if height > image_height: height = image_height r = RECT() r.left = 0 r.top = 2 # offset text a little bit down r.right = r.left + width - 1 r.bottom = r.top + height - 1 # render text to bitmap with Win32GdiBitmap(device_context, width, height) as (bitmap, bitmap_info): old_bitmap = windll.gdi32.SelectObject( device_context, bitmap) assert windll.user32.DrawTextW( device_context, text, -1, ctypes.byref(r), DT_CENTER | DT_VCENTER | DT_NOPREFIX) ctypes.windll.gdi32.SelectObject(device_context, old_bitmap) text_image_buffer = ctypes.create_string_buffer( buffer_length) windll.gdi32.GetDIBits(device_context, bitmap, 0, ctypes.c_uint32(height), ctypes.byref(text_image_buffer), ctypes.byref(bitmap_info), DIB_RGB_COLORS) # extract bitmap pixels to array text_image_bytes = np.frombuffer(text_image_buffer, dtype=np.uint8, count=width * height * 4) # Turn text int pixels to white-over-black floats ordered_text_bytes = np.reshape(text_image_bytes, (height * width, 4)) black_white_rect = [ [1.0, 1.0, 1.0, 1.0] if e[0] > 0 else [0.0, 0.0, 0.0, 1.0] for e in ordered_text_bytes ] return black_white_rect, width, height
def __init__(self): #taskbar self.taskbar = Window.find_window("Shell_TrayWnd") self.startbutton = self.get_startbutton() self.appbarData = APPBARDATA(ctypes.sizeof(APPBARDATA) ,self.taskbar.hWindow ,0 ,0 ,RECT(0,0,0,0) ,0 )
def side_bar_status(self, window, view): layout = window.get_layout() _, c = self.get_layout_rowcol(layout) g2d = self.make_list2d(self.get_group_list(window), c) all_views_width = sum(self.calc_group_offset_width(g2d, c)) rect = RECT() windll.user32.GetClientRect(c_ulong(window.hwnd()), byref(rect)) width = rect.right - all_views_width if width < 0: width = 0 return {'visible': width > 0, 'width': width}
def openClick(self): oldid = self.pptid rect = RECT(int(self.xEdit.text()), int(self.yEdit.text()), int(self.widthEdit.text()), int(self.heightEdit.text())) filename = str(self.pptEdit.text().replace('/', '\\')) folder = str(self.folderEdit.text().replace('/', '\\')) print(filename, folder) self.pptid = self.pptdll.OpenPPT(filename, None, rect, folder) print('id: ' + str(self.pptid)) if oldid >= 0: self.pptdll.ClosePPT(oldid) slides = self.pptdll.GetSlideCount(self.pptid) print('slidecount: ' + str(slides)) self.total.setNum(self.pptdll.GetSlideCount(self.pptid)) self.updateCurrSlide()
def glassExtendInto(win, left = -1, right = -1, top = -1, bottom = -1): """ Extends a top level window's frame glass into the client area by the specified margins. Returns True upon success. If desktop composition is not enabled, this function will do nothing and return False. """ rect = RECT(left, right, top, bottom) if IsCompositionEnabled(): dwm.DwmExtendFrameIntoClientArea(win.Handle, byref(rect)) return True else: return False
def OnAppBarPosChanged(self, wParam, lParam): # log.warning('not implemented: OnAppBarPosChanged') # return log.info('OnAppBarPosChanged') rc, mon = RECT(), monitor_rect(self.win) rc.top = mon.Top rc.left = mon.Left rc.right = mon.Right rc.bottom = mon.Bototm winrect = self.win.Rect iHeight = winrect.Bottom - winrect.Top iWidth = winrect.Right - winrect.Left if self.side == ABE_TOP: rc.bottom = rc.top + iHeight elif self.side == ABE_BOTTOM: rc.top = rc.bottom - iHeight elif self.side == ABE_LEFT: rc.right = rc.left + iWidth elif self.side == ABE_RIGHT: rc.left = rc.right - iWidth;
def wnd_procedure(hwnd, message, w_param, l_param): if message == WM_PAINT: ps = PAINTSTRUCT() rect = RECT() hdc = user32.BeginPaint(hwnd, byref(ps)) user32.GetClientRect(hwnd, byref(rect)) user32.DrawTextW(hdc, u"Ledger SSH Agent", -1, byref(rect), DT_SINGLELINE | DT_CENTER | DT_VCENTER) user32.EndPaint(hwnd, byref(ps)) elif message == WM_DESTROY: user32.PostQuitMessage(0) elif message == WM_QUIT: user32.PostQuitMessage(0) elif message == WM_CREATE: icon_bytes = get_icon_bytes() icon_index = user32.LookupIconIdFromDirectory(icon_bytes, True) icon = user32.CreateIconFromResource(icon_bytes[icon_index:], len(icon_bytes) - icon_index, True, 0x00030000) nid = NOTIFYICONDATA() nid.cbSize = sizeof(NOTIFYICONDATA) nid.hWnd = hwnd nid.uId = 1 nid.uFlags = 1 | 2 | 4 nid.szTip = u"Ledger SSH Agent" nid.uCallbackMessage = WM_APP nid.hIcon = icon shell32.Shell_NotifyIconW(NIM_ADD, byref(nid)) elif message == WM_APP: if l_param == WM_RBUTTONUP: show_popup_menu(hwnd) elif l_param != WM_MOUSEMOVE: hide_popup_menu() elif message == WM_COMMAND: if w_param == ID_PUBLIC: copy_public_key_to_clipboard(hwnd) elif w_param == ID_EXIT: stop(hwnd) elif message == WM_COPYDATA: map_name = read_file_name_from_input(l_param) pymap = MemoryMap(map_name) with pymap: ret = answer_if_device_present(pymap) return ret else: return user32.DefWindowProcW(hwnd, message, w_param, l_param) return 0
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