我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用win32gui.GetWindowRect()。
def Menu(): try: #?? pdhk=win32gui.GetWindowRect(win32gui.FindWindowEx(win32gui.FindWindow('TdxW_MainFrame_Class','???????V7.35 - [???-?????]'),None,'#32770',None)) win32api.SetCursorPos([pdhk[0]+330,pdhk[1]+10]) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) time.sleep(1) #????? win32api.SetCursorPos([pdhk[0]+380,pdhk[1]+20+480]) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) time.sleep(1) except Exception as e: ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e)) #???????->?????
def Free_quotation(): time.sleep(3) try: Tab_handle = win32gui.FindWindowEx(win32gui.FindWindow('#32770','???????V7.35'),None,'SysTabControl32','Tab1') #print(hex(Tab_handle)) #time.sleep(1) p=win32gui.GetWindowRect(Tab_handle) #print(p) #print(p[2]) #print(p[3]) win32api.SetCursorPos([p[0]+170,p[1]+7]) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) time.sleep(1) win32gui.PostMessage(win32gui.FindWindowEx(win32gui.FindWindow('#32770','???????V7.35'),None,'Button','??'),win32con.BM_CLICK,0,0) time.sleep(3) except Exception as e: ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e)) #?????
def _DoSize(self, cx, cy, repaint = 1): # right-justify the textbox. ctrl = win32gui.GetDlgItem(self.hwnd, IDC_SEARCHTEXT) l, t, r, b = win32gui.GetWindowRect(ctrl) l, t = win32gui.ScreenToClient(self.hwnd, (l,t) ) r, b = win32gui.ScreenToClient(self.hwnd, (r,b) ) win32gui.MoveWindow(ctrl, l, t, cx-l-5, b-t, repaint) # The button. ctrl = win32gui.GetDlgItem(self.hwnd, IDC_BUTTON_DISPLAY) l, t, r, b = win32gui.GetWindowRect(ctrl) l, t = win32gui.ScreenToClient(self.hwnd, (l,t) ) r, b = win32gui.ScreenToClient(self.hwnd, (r,b) ) list_y = b + 10 w = r - l win32gui.MoveWindow(ctrl, cx - 5 - w, t, w, b-t, repaint) # The list control win32gui.MoveWindow(self.hwndList, 0, list_y, cx, cy-list_y, repaint) # The last column of the list control. new_width = cx - win32gui.SendMessage(self.hwndList, commctrl.LVM_GETCOLUMNWIDTH, 0) win32gui.SendMessage(self.hwndList, commctrl.LVM_SETCOLUMNWIDTH, 1, new_width)
def selectComboboxItemThird(hwnd, item): try: # item is an index Use this to select 0 + item win32gui.SendMessage(hwnd, win32con.CB_SHOWDROPDOWN, 1, 0) win32gui.SendMessage(hwnd, win32con.CB_SETCURSEL, item, 0) win32gui.SendMessage(hwnd, win32con.WM_SETFOCUS, 0, 0 ) time.sleep(1) tmp=win32gui.GetWindowRect(hwnd) #print 'selectComboboxItemThird',tmp ''' win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,tmp[0]+1, tmp[1]+1) time.sleep(0.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,tmp[0]+1, tmp[1]+1) ''' win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, 13, 0 ) time.sleep(0.1) win32gui.SendMessage(hwnd, win32con.WM_KEYUP, 13, 0 ) time.sleep(0.1) #_sendNotifyMessage(hwnd, win32con.CBN_SELCHANGE) except TypeError: # Item is a string - find the index, and use that items = getComboboxItems(hwnd) itemIndex = items.index(item) selectComboboxItem(hwnd, itemIndex)
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 CFQS(): try: e = win32gui.GetWindowRect (win32gui.FindWindowEx(win32gui.FindWindowEx(win32gui.FindWindow('#32770','???????'),None,'#32770','???????'),None,'SysListView32','CFQS')) win32api.SetCursorPos([e[0]+50,e[1]+25]) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0) time.sleep(1) except Exception as e: ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e)) #????
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 rect(self): hwnd = self.hwnd if not self.exclude_border: left, top, right, bottom = win32gui.GetWindowRect(hwnd) else: _left, _top, _right, _bottom = win32gui.GetClientRect(hwnd) left, top = win32gui.ClientToScreen(hwnd, (_left, _top)) right, bottom = win32gui.ClientToScreen(hwnd, (_right, _bottom)) return Rect(left, top, right, bottom)
def __init_rect_size(self): hwnd = self.hwnd left, top, right, bottom = win32gui.GetWindowRect(hwnd) if self.exclude_border: _left, _top, _right, _bottom = win32gui.GetClientRect(hwnd) left, top = win32gui.ClientToScreen(hwnd, (_left, _top)) right, bottom = win32gui.ClientToScreen(hwnd, (_right, _bottom)) self._rect = Rect(left, top, right, bottom) self._size = Size(right-left, bottom-top)
def bringToTop(self): if platform.system() == "Windows": self.showNormal() self.raise_() self.activateWindow() try: import win32con import win32gui hwnd = self.effectiveWinId() rect = win32gui.GetWindowRect(hwnd) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y # mark it "always on top", just for a moment, to force it to the top win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST, x, y, w, h, 0) win32gui.SetWindowPos(hwnd,win32con.HWND_NOTOPMOST, x, y, w, h, 0) except Exception as e: print "Whoops", e elif platform.system() == "Darwin": self.raise_() self.showNormal() self.activateWindow() else: flags = self.windowFlags() self.setWindowFlags( flags | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.X11BypassWindowManagerHint) QtCore.QCoreApplication.processEvents() #self.show() self.setWindowFlags( flags ) self.show()
def _get_rect(self): ret = win32gui.GetWindowRect(self._hwnd) return Rect(ret[0], ret[1], ret[2] - ret[0], ret[3] - ret[1])
def __init__(self, _hwnd): self.hwnd = _hwnd left, top, right, bot = win32gui.GetWindowRect(self.hwnd) self.w = right - left self.h = bot - top self.hwndDC = win32gui.GetWindowDC(self.hwnd) self.mfcDC = win32ui.CreateDCFromHandle(self.hwndDC) self.saveDC = self.mfcDC.CreateCompatibleDC()
def getstate(self): win32gui.SetForegroundWindow(self.hwnd) bbox = win32gui.GetWindowRect(self.hwnd) img = ImageGrab.grab(bbox) img = img.resize([84, 84], Image.ANTIALIAS) pilim = np.array(img, dtype=np.uint8) pilim = rgb2gray(pilim) return pilim
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 GetScreenImg(self): ''' Gets the screen of the window referenced by self.hwnd ''' if self.hwnd is None: raise Exception("HWND is none. HWND not called or invalid window name provided.") self.l, self.t, self.r, self.b = win32gui.GetWindowRect(self.hwnd) #Remove border around window (8 pixels on each side) #Remove 4 extra pixels from left and right 16 + 8 = 24 w = self.r - self.l - self.br - self.bl #Remove border on top and bottom (31 on top 8 on bottom) #Remove 12 extra pixels from bottom 39 + 12 = 51 h = self.b - self.t - self.bt - self.bb wDC = win32gui.GetWindowDC(self.hwnd) dcObj = win32ui.CreateDCFromHandle(wDC) cDC = dcObj.CreateCompatibleDC() dataBitMap = win32ui.CreateBitmap() dataBitMap.CreateCompatibleBitmap(dcObj, w, h) cDC.SelectObject(dataBitMap) #First 2 tuples are top-left and bottom-right of destination #Third tuple is the start position in source cDC.BitBlt((0,0), (w, h), dcObj, (self.bl, self.bt), win32con.SRCCOPY) bmInfo = dataBitMap.GetInfo() im = np.frombuffer(dataBitMap.GetBitmapBits(True), dtype = np.uint8) dcObj.DeleteDC() cDC.DeleteDC() win32gui.ReleaseDC(self.hwnd, wDC) win32gui.DeleteObject(dataBitMap.GetHandle()) #Bitmap has 4 channels like: BGRA. Discard Alpha and flip order to RGB #31 pixels from border on top, 8 on bottom #8 pixels from border on the left and 8 on right #Remove 1 additional pixel from left and right so size is 1278 | 9 #Remove 14 additional pixels from bottom so size is 786 | 6 #return im.reshape(bmInfo['bmHeight'], bmInfo['bmWidth'], 4)[31:-22, 9:-9, -2::-1] #For 800x600 images: #Remove 12 pixels from bottom + border #Remove 4 pixels from left and right + border return im.reshape(bmInfo['bmHeight'], bmInfo['bmWidth'], 4)[:, :, -2::-1]
def get_window_rect(hwnd): """ Gets the window's dimensions in the form Rect(x, y, w, h). Args: hwnd (int): The window handler. Returns: (Rect(x, y, w, h)): The dimensions of the window. """ rect = wg.GetWindowRect(hwnd) return Rect(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1])
def set_window_top(): hwnd = win32gui.GetForegroundWindow() (left, top, right, bottom) = win32gui.GetWindowRect(hwnd) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, left, top, right - left, bottom - top, 0)
def clickWindow(hwnd, offset): left, top, right, bottom = win32gui.GetWindowRect(hwnd) # print('left, top, right, bottom', left, top, right, bottom) win32api.SetCursorPos([left + offset, (bottom - top) // 2 + top]) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) time.sleep(0.2) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) time.sleep(0.2)
def invisible_click_rel(self,handle,pos, button_name="left"): """Click in window coordinates without moving mouse""" #get window info xleft, ytop, xright, ybottom = win32gui.GetWindowRect(handle) xcur,ycur = win32gui.GetCursorPos() ctypes.windll.user32.SetCursorPos(pos[0]+xleft,pos[1]+ytop) self.click((pos[0]+xleft,pos[1]+ytop),button_name) ctypes.windll.user32.SetCursorPos(xcur,ycur)
def _click_login_verify_code(self): input_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x56ba) rect = win32gui.GetWindowRect(input_hwnd) self._mouse_click(rect[0] + 5, rect[1] + 5)
def _grab_verify_code(self): verify_code_hwnd = win32gui.GetDlgItem(self.login_hwnd, 0x56ba) self._set_foreground_window(self.login_hwnd) time.sleep(1) rect = win32gui.GetWindowRect(verify_code_hwnd) return ImageGrab.grab(rect)
def set_always_on_top(val): global windowsWindow global isOnTop if isWindows: if windowsWindow: rect = win32gui.GetWindowRect(windowsWindow) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y placement = win32gui.GetWindowPlacement(windowsWindow) if val is True: win32gui.SetWindowPos(windowsWindow, win32con.HWND_TOPMOST, x, y, w, h, placement[1]) isOnTop = True # win32gui.SetFocus(windowsWindow) else: win32gui.SetWindowPos(windowsWindow, win32con.HWND_NOTOPMOST, x, y, w, h, placement[1]) isOnTop = False return True else: print("Window with title 'Google It Up!' doesnt exist") return False elif isMac: # Not working, dont try command = "/usr/bin/osascript -e 'tell app \"System Events\"' " command += "-e 'set theApps to every process whose name contains \"Google It Up!\"' " command += "-e 'set theApp to item 1 of theApps' -e 'set frontmost of theApp to true' " command += "-e 'end tell'" if val == False: command = command.replace('true', 'false') os.system(command)
def taskbar(): if platform == 'win': # example: # right side x>0 y=0 (1474, 0, 1536, 864) # left side x=0 y<R/2 ( 0, 0, 62, 864) # top side x=0 y=0 ( 0, 0, 1536, 27) # bot side x=0 y>R/2 ( 0, 837, 1536, 864) # get resolution to get taskbar position res = sys_resolution() # get taskbar rectangle handle = win32gui.FindWindow("Shell_traywnd", None) left, top, right, bottom = win32gui.GetWindowRect(handle) x = y = 0 width, height = res if left: pos = 'right' x = left width = right - left elif right < res['y'] / 2.0: pos = 'left' width = right elif right > res['y'] / 2.0 and not top: pos = 'top' height = bottom elif right > res['y'] / 2.0 and top: pos = 'bottom' y = top height = bottom - top else: x, y, width, height, pos = (0, 0, 0, 0, '') return { 'x': x, 'y': y, 'width': width, 'height': height, 'pos': pos }
def captureAlbumArt(self): while(self.windowHandle != GetForegroundWindow()): SetForegroundWindow(self.windowHandle) time.sleep(WAIT_TIME) ## Give Spotify a moment to come to the foreground ShowWindow(self.windowHandle, SW_SHOWMAXIMIZED) time.sleep(WAIT_TIME) ## Give Spotify a second to become maximized ## Get the edges of the window left, top, right, bottom = GetWindowRect(self.windowHandle) left += self.artOffsets[0] bottom -= self.artOffsets[1] ## Get the album art's location from those edges and user specified offsets. region = (left, bottom - self.artSideLength, left + self.artSideLength, bottom) return pyscreenshot.grab(bbox=region, childprocess=False)
def hwd_get_pos(list,tuple): for x in list: if isinstance(x,(int)): print 'hwd:', x,' pos: ', win32gui.GetWindowRect(x) if win32gui.GetWindowRect(x) ==tuple: return x return 0
def dumpWindow_pos(hwnd): '''Dump all controls from a window into a nested list Useful during development, allowing to you discover the structure of the contents of a window, showing the text and class of all contained controls. Arguments: The window handle of the top level window to dump. Returns A nested list of controls. Each entry consists of the control's hwnd, its text, its class, and its sub-controls, if any. Usage example: replaceDialog = findTopWindow(wantedText='Replace') pprint.pprint(dumpWindow(replaceDialog)) ''' windows = [] try: win32gui.EnumChildWindows(hwnd, _windowEnumerationHandler, windows) except win32gui.error: # No child windows return windows = [list(window) for window in windows] for window in windows: childHwnd, windowText, windowClass = window window_content = dumpWindow(childHwnd) if window_content: window.append(window_content) print '###################' print childHwnd,'pos:',win32gui.GetWindowRect(childHwnd),'window_content:',window_content tuple_t = win32gui.GetWindowRect(childHwnd) if tuple_t[0]==179 and tuple_t[2]==561: print window_content[0][0],'pos:',win32gui.GetWindowRect(window_content[0][0]) if window_content[0][0]: bufLen=1024 buf =win32gui.PyMakeBuffer(bufLen) n = win32gui.SendMessage(window_content[0][0],win32con.WM_GETTEXT,bufLen,buf) str = buf[:n] print str print getEditText(window_content[0][0]) time.sleep(1) #win32gui.SendMessage(window_content[0][0],win32con.WM_SETTEXT,None,'Realtek 10/100/1000 Ethernet NIC') print '###################' return windows
def FX_GetWindowRect(Win32Window): return win32gui.GetWindowRect(Win32Window)
def create_boundingbox(self, hwnd = None, windows_style=False): """ Creates a bounding box of the window. Args: hwnd (int): the window handle we are going to find. If not supplied the hwnd from the last get_hwnd_by_title will be used Returns: Creates a tuple with four elements. The upper left coordinates and the lower right coordinates. (left, top, right,buttom window borders) """ if hwnd is None: hwnd = self.get_hwnd() logging.debug('Trying to find the box for 0x{:2X}'.format(hwnd)) self.bbox = win32gui.GetWindowRect(hwnd) logging.debug('Found {}'.format(self.bbox)) if windows_style: pos_size = self.get_bbox_size(self.get_bbox()) return () else: return self.bbox