我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用win32gui.GetDesktopWindow()。
def __init__(self, window_name=None, exe_file=None, exclude_border=True): hwnd = 0 # first check window_name if window_name is not None: hwnd = win32gui.FindWindow(None, window_name) if hwnd == 0: def callback(h, extra): if window_name in win32gui.GetWindowText(h): extra.append(h) return True extra = [] win32gui.EnumWindows(callback, extra) if extra: hwnd = extra[0] if hwnd == 0: raise WindowsAppNotFoundError("Windows Application <%s> not found!" % window_name) # check exe_file by checking all processes current running. elif exe_file is not None: pid = find_process_id(exe_file) if pid is not None: def callback(h, extra): if win32gui.IsWindowVisible(h) and win32gui.IsWindowEnabled(h): _, p = win32process.GetWindowThreadProcessId(h) if p == pid: extra.append(h) return True return True extra = [] win32gui.EnumWindows(callback, extra) #TODO: get main window from all windows. if extra: hwnd = extra[0] if hwnd == 0: raise WindowsAppNotFoundError("Windows Application <%s> is not running!" % exe_file) # if window_name & exe_file both are None, use the screen. if hwnd == 0: hwnd = win32gui.GetDesktopWindow() self.hwnd = hwnd self.exclude_border = exclude_border
def grab_screen(region=None): hwin = win32gui.GetDesktopWindow() if region: left,top,x2,y2 = region width = x2 - left + 1 height = y2 - top + 1 else: width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) signedIntsArray = bmp.GetBitmapBits(True) img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height,width,4) srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(hwin, hwindc) win32gui.DeleteObject(bmp.GetHandle()) return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
def OnInitDialog(self, hwnd, msg, wparam, lparam): self.hwnd = hwnd desktop = win32gui.GetDesktopWindow() dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop) centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)/2, (dt_b-dt_t)/2) ) bmCtrl = win32gui.GetDlgItem(self.hwnd, IDC_BITMAP) win32gui.SendMessage(bmCtrl, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, self.hSplash) win32gui.SetWindowPos(self.hwnd, win32con.HWND_TOPMOST, centre_x-(self.bmWidth/2), centre_y-(self.bmHeight/2), self.bmWidth, self.bmHeight, win32con.SWP_HIDEWINDOW) win32gui.SetForegroundWindow(self.hwnd)
def grab_screen(region=None, title=None): hwin = win32gui.GetDesktopWindow() if region: left,top,x2,y2 = region width = x2 - left + 1 height = y2 - top + 1 elif title: gtawin = win32gui.FindWindow(None, title) if not gtawin: raise Exception('window title not found') #get the bounding box of the window left, top, x2, y2 = win32gui.GetWindowRect(gtawin) width = x2 - left +1 height = y2 - top +1 else: width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) signedIntsArray = bmp.GetBitmapBits(True) img = np.fromstring(signedIntsArray, dtype='uint8') img.shape = (height,width,4) srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(hwin, hwindc) win32gui.DeleteObject(bmp.GetHandle()) return cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
def __init_screen_handles(self): # opengl windows cannot get from it's hwnd, so we use the screen hwnd = win32gui.GetDesktopWindow() # get screen size and offset left, top, right, bottom = self.rect width, height = right-left, bottom-top # the device context of the window hdcwin = win32gui.GetWindowDC(hwnd) # make a temporary dc hdcmem = win32gui.CreateCompatibleDC(hdcwin) # make a temporary bitmap in memory, this is a PyHANDLE object hbmp = win32gui.CreateCompatibleBitmap(hdcwin, width, height) # select bitmap for temporary dc win32gui.SelectObject(hdcmem, hbmp) # check the bitmap object infomation bmp = win32gui.GetObject(hbmp) bi = BITMAPINFOHEADER() bi.biSize = ctypes.sizeof(BITMAPINFOHEADER) bi.biWidth = bmp.bmWidth bi.biHeight = bmp.bmHeight bi.biPlanes = bmp.bmPlanes bi.biBitCount = bmp.bmBitsPixel bi.biCompression = 0 # BI_RGB bi.biSizeImage = 0 bi.biXPelsPerMeter = 0 bi.biYPelsPerMeter = 0 bi.biClrUsed = 0 bi.biClrImportant = 0 # calculate total size for bits pixel = bmp.bmBitsPixel size = ((bmp.bmWidth * pixel + pixel - 1)/pixel) * 4 * bmp.bmHeight buf = (ctypes.c_char * size)() self._hdcwin = hdcwin self._hdcmem = hdcmem self._bi = bi self._hbmp = hbmp self._buf = buf
def screen(self): """PIL Image of current window screen. reference: https://msdn.microsoft.com/en-us/library/dd183402(v=vs.85).aspx""" hwnd = win32gui.GetDesktopWindow() left, top, right, bottom = self.rect width, height = right-left, bottom-top # copy bits to temporary dc win32gui.BitBlt(self._hdcmem, 0, 0, width, height, self._hdcwin, left, top, win32con.SRCCOPY) # read bits into buffer windll.gdi32.GetDIBits(self._hdcmem, self._hbmp.handle, 0, height, self._buf, ctypes.byref(self._bi), win32con.DIB_RGB_COLORS) # make a PIL Image img = Image.frombuffer('RGB', (width, height), self._buf, 'raw', 'BGRX', 0, 1) img = img.transpose(Image.FLIP_TOP_BOTTOM) return img
def screen_cv2(self): """cv2 Image of current window screen""" hwnd = win32gui.GetDesktopWindow() left, top, right, bottom = self.rect width, height = right-left, bottom-top # copy bits to temporary dc win32gui.BitBlt(self._hdcmem, 0, 0, width, height, self._hdcwin, left, top, win32con.SRCCOPY) # read bits into buffer windll.gdi32.GetDIBits(self._hdcmem, self._hbmp.handle, 0, height, self._buf, ctypes.byref(self._bi), win32con.DIB_RGB_COLORS) # make a cv2 Image arr = np.fromstring(self._buf, dtype=np.uint8) img = arr.reshape(height, width, 4) img = img[::-1,:, 0:3] return img
def OnInitDialog(self, hwnd, msg, wparam, lparam): self.hwnd = hwnd # centre the dialog desktop = win32gui.GetDesktopWindow() l,t,r,b = win32gui.GetWindowRect(self.hwnd) dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop) centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)//2, (dt_b-dt_t)//2) ) win32gui.MoveWindow(hwnd, centre_x-(r//2), centre_y-(b//2), r-l, b-t, 0) self._SetupList() l,t,r,b = win32gui.GetClientRect(self.hwnd) self._DoSize(r-l,b-t, 1)
def OnInitDialog(self, hwnd, msg, wparam, lparam): self.hwnd = hwnd # centre the dialog desktop = win32gui.GetDesktopWindow() l,t,r,b = win32gui.GetWindowRect(self.hwnd) dt_l, dt_t, dt_r, dt_b = win32gui.GetWindowRect(desktop) centre_x, centre_y = win32gui.ClientToScreen( desktop, ( (dt_r-dt_l)//2, (dt_b-dt_t)//2) ) win32gui.MoveWindow(hwnd, centre_x-(r//2), centre_y-(b//2), r-l, b-t, 0)
def GetHWND(self, wname = None): ''' Gets handle of window to view wname: Title of window to find Return: True on success; False on failure ''' if wname is None: self.hwnd = win32gui.GetDesktopWindow() else: self.hwnd = win32gui.FindWindow(None, wname) if self.hwnd == 0: self.hwnd = None return False self.l, self.t, self.r, self.b = win32gui.GetWindowRect(self.hwnd) return True
def screen(self): """PIL Image of current window screen. (the window must be on the top) reference: https://msdn.microsoft.com/en-us/library/dd183402(v=vs.85).aspx""" # opengl windows cannot get from it's hwnd, so we use the screen hwnd = win32gui.GetDesktopWindow() # get window size and offset left, top, right, bottom = self.rect width, height = right-left, bottom-top # the device context of the window hdcwin = win32gui.GetWindowDC(hwnd) # make a temporary dc hdcmem = win32gui.CreateCompatibleDC(hdcwin) # make a temporary bitmap in memory, this is a PyHANDLE object hbmp = win32gui.CreateCompatibleBitmap(hdcwin, width, height) # select bitmap for temporary dc win32gui.SelectObject(hdcmem, hbmp) # copy bits to temporary dc win32gui.BitBlt(hdcmem, 0, 0, width, height, hdcwin, left, top, win32con.SRCCOPY) # check the bitmap object infomation bmp = win32gui.GetObject(hbmp) bi = BITMAPINFOHEADER() bi.biSize = ctypes.sizeof(BITMAPINFOHEADER) bi.biWidth = bmp.bmWidth bi.biHeight = bmp.bmHeight bi.biPlanes = bmp.bmPlanes bi.biBitCount = bmp.bmBitsPixel bi.biCompression = 0 # BI_RGB bi.biSizeImage = 0 bi.biXPelsPerMeter = 0 bi.biYPelsPerMeter = 0 bi.biClrUsed = 0 bi.biClrImportant = 0 # calculate total size for bits pixel = bmp.bmBitsPixel size = ((bmp.bmWidth * pixel + pixel - 1)/pixel) * 4 * bmp.bmHeight buf = (ctypes.c_char * size)() # read bits into buffer windll.gdi32.GetDIBits(hdcmem, hbmp.handle, 0, bmp.bmHeight, buf, ctypes.byref(bi), win32con.DIB_RGB_COLORS) # make a PIL Image img = Image.frombuffer('RGB', (bmp.bmWidth, bmp.bmHeight), buf, 'raw', 'BGRX', 0, 1) img = img.transpose(Image.FLIP_TOP_BOTTOM) # cleanup win32gui.DeleteObject(hbmp) win32gui.DeleteObject(hdcmem) win32gui.ReleaseDC(hwnd, hdcwin) return img
def run(self): try: if self.mode != "dir": args = {} if self.path: args["InitialDir"] = os.path.dirname(self.path) path = os.path.splitext(os.path.dirname(self.path)) args["File"] = path[0] args["DefExt"] = path[1] args["Title"] = self.title if self.title else "Pick a file..." args["CustomFilter"] = 'Other file types\x00*.*\x00' args["FilterIndex"] = 1 filters = "" for f in self.filters: if type(f) == str: filters += (f + "\x00") * 2 else: filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00" args["Filter"] = filters flags = (win32con.OFN_EXTENSIONDIFFERENT | win32con.OFN_OVERWRITEPROMPT) if self.multiple: flags |= win32con.OFN_ALLOWmultiple | win32con.OFN_EXPLORER if self.show_hidden: flags |= win32con.OFN_FORCESHOWHIDDEN args["Flags"] = flags if self.mode == "open": self.fname, _, _ = win32gui.GetOpenFileNameW(**args) elif self.mode == "save": self.fname, _, _ = win32gui.GetSaveFileNameW(**args) if self.fname: if self.multiple: seq = str(self.fname).split("\x00") dir_n, base_n = seq[0], seq[1:] self.selection = [os.path.join(dir_n, i) for i in base_n] else: self.selection = str(self.fname).split("\x00") else: # From http://goo.gl/UDqCqo pidl, display_name, image_list = shell.SHBrowseForFolder( win32gui.GetDesktopWindow(), None, self.title if self.title else "Pick a folder...", 0, None, None ) self.selection = [str(shell.SHGetPathFromIDList(pidl))] return self.selection except (RuntimeError, pywintypes.error): return None
def get_hwnd_by_title_class(self, class_text = None, title_text= None, parent_title = None,parent_class = None): """ Returns a windows window_handler Args: title_text (string): the title of the window we are looking for SPECIAL CASE: if "desktop:n" is given, a handle to the desktop number n handle is given Returns: int: the handler for the window if found Raises: win32.error: If the windowtitle is invalid """ if 'desktop:' in title_text.lower(): _ , num = title_text.lower().split(':',1) num = int(num) monitors = win32api.EnumDisplayMonitors() tar_mon = monitors[num] self.hwnd = tar_mon[1] return self.hwnd if title_text.lower() == "desktop": self.hwnd = win32gui.GetDesktopWindow() return self.hwnd child_hwnd = [] def child_enumerator(hwnd,param): child_hwnd.append(hwnd) return True if parent_title is not None or parent_class is not None: logging.debug("Where supplied title/class: {0}/{1}".format(str(title_text), str(class_text))) parent_hwnd = self.get_hwnd_by_title_class(class_text=parent_class,title_text=parent_title) win32gui.EnumChildWindows(parent_hwnd,child_enumerator,None) for hwnd in child_hwnd: hwnd_title = win32gui.GetWindowText(hwnd) hwnd_class = win32gui.GetClassName(hwnd) if (hwnd_title == title_text and title_text is not None) or \ (hwnd_class == class_text and class_text is not None): self.hwnd = hwnd return hwnd # logging.debug("Found parent with title/class {0}{1} at {2}".format(parent_title,parent_class,parent_hwnd)) # self.hwnd = win32gui.FindWindowEx(parent_hwnd,0,class_text,title_text) else: logging.debug("Where supplied title/class: {0}/{1}".format(str(title_text), str(class_text))) self.hwnd = win32gui.FindWindow(class_text, title_text) if self.hwnd == 0: raise ValueError('Unable to find a window with that title or class') logging.debug("Found window 0x{:2X}".format(self.hwnd)) return self.hwnd