def capture_window(name): ''' Return captured window in RGBA format (numpy array) ''' hwnd = win32gui.FindWindow(None, name) cr = win32gui.GetClientRect(hwnd) #leftTop = win32gui.ClientToScreen(hwnd, (cr[0], cr[1])) width = cr[2] height = cr[3] hDC = win32gui.GetDC(hwnd) myDC = win32ui.CreateDCFromHandle(hDC) newDC = myDC.CreateCompatibleDC() mybitmap = win32ui.CreateBitmap() mybitmap.CreateCompatibleBitmap(myDC, width, height) newDC.SelectObject(mybitmap) # win32gui.SetForegroundWindow(hwnd) newDC.BitBlt((0, 0), (width, height), myDC, (0, 0), win32con.SRCCOPY) bminfo = mybitmap.GetInfo() signedintarray = mybitmap.GetBitmapBits(True) img = np.fromstring(signedintarray, dtype='uint8') img = img.reshape(bminfo['bmHeight'], bminfo['bmWidth'], 4) img = img[..., [2, 1, 0, 3]] # convert BGRA to RGBA myDC.DeleteDC() newDC.DeleteDC() win32gui.ReleaseDC(hwnd, hDC) win32gui.DeleteObject(mybitmap.GetHandle()) return img
def __init__(self, hwnd, quit_game_enable=1): ''' 初始化 :param hwnd: 需要绑定的窗口句柄 :param quit_game_enable: 程序死掉时是否退出游戏。True为是,False为否 ''' self.run = True self.hwnd = hwnd self.quit_game_enable = quit_game_enable self.debug_enable = False l1, t1, r1, b1 = win32gui.GetWindowRect(self.hwnd) #print(l1,t1, r1,b1) l2, t2, r2, b2 = win32gui.GetClientRect(self.hwnd) # print(l2,t2,r2,b2) self._client_h = b2 - t2 self._client_w = r2 - l2 self._border_l = ((r1 - l1) - (r2 - l2)) // 2 self._border_t = ((b1 - t1) - (b2 - t2)) - self._border_l conf = configparser.ConfigParser() conf.read('conf.ini') self.client = conf.getint('DEFAULT', 'client') if self.client == 1: os.system('adb connect 127.0.0.1:7555') os.system('adb devices')
def get_window_screenshot(self, hwnd, flag): # hwnd = win32gui.FindWindow(None, '계산기') # Change the line below depending on whether you want the whole window # or just the client area. left, top, right, bot = win32gui.GetClientRect(hwnd) # left, top, right, bot = win32gui.GetWindowRect(hwnd) w = right - left h = bot - top hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) # Change the line below depending on whether you want the whole window # or just the client area. result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), flag) # result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC) return im
def wndProc(self, hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: hDC, paintStruct = win32gui.BeginPaint(hWnd) folder_with_ico_file = 'share' if hasattr(sys, 'frozen') else 'windows' filename = os.path.join(os.path.dirname(sys.argv[0]), folder_with_ico_file, 'bleachbit.ico') flags = win32con.LR_LOADFROMFILE hIcon = win32gui.LoadImage(0, filename, win32con.IMAGE_ICON, 0, 0, flags) # Default icon size seems to be 32 pixels so we center the icon vertically. default_icon_size = 32 icon_top_margin = self._splash_screen_height - 2 * ( default_icon_size + 2) win32gui.DrawIcon(hDC, 0, icon_top_margin, hIcon) # win32gui.DrawIconEx(hDC, 0, 0, hIcon, 64, 64, 0, 0, win32con.DI_NORMAL) rect = win32gui.GetClientRect(hWnd) textmetrics = win32gui.GetTextMetrics(hDC) text_left_margin = 2 * default_icon_size text_rect = (text_left_margin, (rect[3] - textmetrics['Height']) // 2, rect[2], rect[3]) win32gui.DrawText(hDC, _("BleachBit is starting...\n"), -1, text_rect, win32con.DT_WORDBREAK) win32gui.EndPaint(hWnd, paintStruct) return 0 elif message == win32con.WM_DESTROY: win32gui.PostQuitMessage(0) return 0 else: return win32gui.DefWindowProc(hWnd, message, wParam, lParam)
def wndProc(hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: hdc, paintStruct = win32gui.BeginPaint(hWnd) print 'windProc' dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0 fontSize = 80 # http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx lf = win32gui.LOGFONT() lf.lfFaceName = "Times New Roman" lf.lfHeight = int(round(dpiScale * fontSize)) #lf.lfWeight = 150 # Use nonantialiased to remove the white edges around the text. # lf.lfQuality = win32con.NONANTIALIASED_QUALITY hf = win32gui.CreateFontIndirect(lf) win32gui.SelectObject(hdc, hf) rect = win32gui.GetClientRect(hWnd) # http://msdn.microsoft.com/en-us/library/windows/desktop/dd162498(v=vs.85).aspx win32gui.DrawText( hdc, 'O', -1, rect, win32con.DT_CENTER | win32con.DT_NOCLIP | win32con.DT_SINGLELINE | win32con.DT_VCENTER ) win32gui.EndPaint(hWnd, paintStruct) return 0 elif message == win32con.WM_DESTROY: print 'Closing the window.' win32gui.PostQuitMessage(0) return 0 else: return win32gui.DefWindowProc(hWnd, message, wParam, lParam)
def screenshot(handle): left, top, right, bot = win32gui.GetClientRect(handle) w = right - left h = bot - top hwndDC = win32gui.GetWindowDC(handle) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, w - 200, h - 200) saveDC.SelectObject(saveBitMap) windll.user32.PrintWindow(handle, saveDC.GetSafeHdc(), 1) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(handle, hwndDC) return im
def WndProc(self, hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: rect = win32gui.GetClientRect(hWnd) # tuple(L,T,R,B) hDC, paintStruct = win32gui.BeginPaint(hWnd) win32gui.SetTextColor(hDC, win32api.RGB(255, 0, 0)) win32gui.SetBkMode(hDC, 1) rect2 = (rect[0] + 10, rect[1] + 10, rect[2], rect[3]) rect3 = (rect[0] + 10, rect[1] + 30, rect[2], rect[3]) win32gui.DrawText(hDC, 'Overlay Test', -1, rect2, win32con.DT_SINGLELINE | win32con.DT_NOCLIP) win32gui.DrawText(hDC, 'Test message2', -1, rect3, win32con.DT_SINGLELINE | win32con.DT_NOCLIP) ### memDC = win32gui.CreateCompatibleDC(hDC) image1 = win32gui.LoadImage(None, "1111.bmp", win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE) OldBitmap = win32gui.SelectObject(memDC, image1) if image1 == 0: print("image load error") exit(1) win32gui.BitBlt(hDC, 10, 50, 100, 100, memDC, 0, 0, win32con.SRCCOPY) win32gui.SelectObject(memDC, OldBitmap) win32gui.DeleteObject(image1) win32gui.DeleteObject(memDC) win32gui.EndPaint(hWnd, paintStruct) elif message == win32con.WM_DESTROY: print("Being destroyed") win32gui.PostQuitMessage(0) else: return win32gui.DefWindowProc(hWnd, message, wParam, lParam)
def stop_listener(self): self.stop_thread = True print('STOP signal sent| waiting for thread to quit!') self.thread.join() dr = DataReceiver() dr.run_listener() time.sleep(0.1) mapImage = cv2.imread('../dust2.jpg') while True: hdesktop = win32gui.FindWindow(None, windowname) left, top, right, bot = win32gui.GetClientRect(hdesktop) width = right - left height = bot - top top += tshift left += lshift desktop_dc = win32gui.GetWindowDC(hdesktop) img_dc = win32ui.CreateDCFromHandle(desktop_dc) mem_dc = img_dc.CreateCompatibleDC() screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, width, height) mem_dc.SelectObject(screenshot) mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) im = Image.frombuffer( 'RGB',
def get_title_bar_height(hwnd): _, top, _, bottom = win32gui.GetWindowRect(hwnd) _, _, _, a_bottom = win32gui.GetClientRect(hwnd) return bottom - a_bottom - top
def get_game_window(auto=False): windows = [] def foreach_window(hwnd, lParam): nonlocal windows if win32gui.IsWindowVisible(hwnd): window_text = win32gui.GetWindowText(hwnd) if "League of Angels" in window_text: windows.append((hwnd, window_text)) logging.debug("Found game window hwnd: {0} title: {1}".format( hwnd, window_text)) return True win32gui.EnumWindows(foreach_window, None) if len(windows) == 0: logging.error("Failed to find game window.") sys.exit(1) elif len(windows) > 1 and not auto: print("Found {0} possible game windows.".format(len(windows))) for i in range(1, len(windows) + 1): print("{0}: {1}".format(i, windows[i - 1][1])) windownum = input( "Enter the number for the window you which to use [1]: ") if windownum == "": windownum = 0 else: windownum = int(windownum) - 1 logging.info("Using window {0}".format(windows[windownum][1])) game_hwnd = windows[windownum][0] else: game_hwnd = windows[0][0] # Ugly hack to let us set foreground window. shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys('%') # Make this window active. win32gui.SetWindowPos( game_hwnd, win32con.HWND_TOP, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE + win32con.SWP_SHOWWINDOW) win32gui.SetForegroundWindow(game_hwnd) win32gui.ShowWindow(game_hwnd, win32con.SW_RESTORE) time.sleep(0.050) windowleft, windowtop, windowright, windowbottom = win32gui.GetWindowRect( game_hwnd) clientleft, clienttop, clientright, clientbottom = win32gui.GetClientRect( game_hwnd) logging.debug("Window position: {},{},{},{}".format( windowleft, windowtop, windowright, windowbottom)) if windowleft < 0: windowleft = 0 if windowtop < 0: windowtop = 0 top = -1 left = -1 right, bottom = win32gui.ClientToScreen(game_hwnd, (clientright, clientbottom)) screengrab = ImageGrab.grab() # Let's find the left edge blackcount = 0 for x in range(windowleft + 5, windowleft + 200): p = screengrab.getpixel((x, windowtop + 300)) if p[0] == 0 and p[1] == 0 and p[2] == 0: blackcount += 1 else: if blackcount > 10: left = x break else: blackcount = 0 if left == -1: logging.error("Failed to find left edge.") sys.exit(1) # Let's find the top edge for y in range(windowtop + 300, windowtop - 1, -1): p = screengrab.getpixel((left - 1, y)) if p[0] != 0 or p[1] != 0 or p[2] != 0: top = y + 1 break if top == -1: logging.debug("Pixels were black to 0, assuming full screen.") top = 0 # Let's find the bottom edge for y in range(bottom - 20, bottom, +1): p = screengrab.getpixel((left - 1, y)) if p[0] != 0 or p[1] != 0 or p[2] != 0: bottom = y break # TODO: Figure out right , currently it's frequently off by several pixels for chrome. logging.debug("Game position: {},{},{},{}".format(left, top, right, bottom)) return left, top, right, bottom
def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_SIZE: self.OnSize, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "test_explorer_browser" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE self.hwnd = win32gui.CreateWindow(classAtom, "Python IExplorerBrowser demo", style, \ 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \ 0, 0, hinst, None) eb = pythoncom.CoCreateInstance(shellcon.CLSID_ExplorerBrowser, None, pythoncom.CLSCTX_ALL, shell.IID_IExplorerBrowser) # as per MSDN docs, hook up events early self.event_cookie = eb.Advise(wrap(EventHandler())) eb.SetOptions(shellcon.EBO_SHOWFRAMES) rect = win32gui.GetClientRect(self.hwnd) # Set the flags such that the folders autoarrange and non web view is presented flags = (shellcon.FVM_LIST, shellcon.FWF_AUTOARRANGE | shellcon.FWF_NOWEBVIEW) eb.Initialize(self.hwnd, rect, (0, shellcon.FVM_DETAILS)) if len(sys.argv) == 2: # If an arg was specified, ask the desktop parse it. # You can pass anything explorer accepts as its '/e' argument - # eg, "::{guid}\::{guid}" etc. # "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" is "My Computer" pidl = shell.SHGetDesktopFolder().ParseDisplayName( 0, None, sys.argv[1])[1] else: # And start browsing at the root of the namespace. pidl = [] eb.BrowseToIDList(pidl, shellcon.SBSP_ABSOLUTE) # and for some reason the "Folder" view in the navigator pane doesn't # magically synchronize itself - so let's do that ourself. # Get the tree control. sp = eb.QueryInterface(pythoncom.IID_IServiceProvider) try: tree = sp.QueryService(shell.IID_INameSpaceTreeControl, shell.IID_INameSpaceTreeControl) except pythoncom.com_error as exc: # this should really only fail if no "nav" frame exists... print("Strange - failed to get the tree control even though " \ "we asked for a EBO_SHOWFRAMES") print(exc) else: # get the IShellItem for the selection. si = shell.SHCreateItemFromIDList(pidl, shell.IID_IShellItem) # set it to selected. tree.SetItemState(si, shellcon.NSTCIS_SELECTED, shellcon.NSTCIS_SELECTED) # eb.FillFromObject(None, shellcon.EBF_NODROPTARGET); # eb.SetEmptyText("No known folders yet..."); self.eb = eb
def get_client_size(self): win_rect = win32gui.GetClientRect(self.window_handle) return win_rect[2] - win_rect[0], win_rect[3] - win_rect[ 1] # width, height
def rect(self): return win32gui.GetClientRect(self.hwnd) if not self.debug else [ 0, 0, self.EMULATOR_WIDTH, self.EMULATOR_HEIGHT ]
def resizeWindow(width, height): fw = win32gui.GetForegroundWindow() wr = win32gui.GetWindowRect(fw) cr = win32gui.GetClientRect(fw) win32gui.MoveWindow(fw, 0, 0, width, height, True)
def getWindowDims(): fw = win32gui.GetForegroundWindow() wr = win32gui.GetWindowRect(fw) cr = win32gui.GetClientRect(fw) return wr, cr
def _get_screenshot(self, window_title): """ Get the pq hwnd """ hwnd = self._get_hwnd(window_title) # Get a DC for the client area of the window clientHandle = win32gui.GetDC(hwnd) clientDC = win32ui.CreateDCFromHandle(clientHandle) # Make and connect DC and bitmap for the screenshot image shotDC = clientDC.CreateCompatibleDC() l,t,r,b = win32gui.GetClientRect(hwnd) h = b-t w = r-l bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(clientDC, w, h) shotDC.SelectObject(bmp) # Copy the client area into the screenshot DC dest_offset = (0,0) size = (w, h) src_offset = (0,0) raster = win32con.SRCCOPY # Make window visible and copy it. Certainly kludgy try: #allow it to whack the window without dying win32gui.SetForegroundWindow(hwnd) #can trigger permission error ## win32gui.BringWindowToTop(hwnd) #not sure if this helps any ## win32gui.SetFocus(hwnd) #doesn't trigger error without permission like setforegroundwindow ## win32gui.SetActiveWindow(hwnd) #not sure if this helps any except: pass ### someday... sleep(.2) #lame way to allow screen to draw before taking shot shotDC.BitBlt(dest_offset, size, clientDC, src_offset, raster) ###### THIS SHOULD BE REMOVED BUT... LEAVE UNTIL HAVE METHOD ### ###### TO PASS IMAGE WITHOUT A FILE. e.g. PIL for 3.x ### # Scale bitmap if not already a Wx480 resolution if h != 600: h_scaled = 600 ## if w == 1280: ## """ handle non- 4:3 resolutions """ ## w_scaled = 640 ## else: ## """ handle 4:3 and widescreen resolutions (maybe need to split) """ w_scaled = 800 #int(round(w * h_scaled / h)) #kludge until scale invariant working scaledDC = shotDC.CreateCompatibleDC() bmp_scaled = win32ui.CreateBitmap() bmp_scaled.CreateCompatibleBitmap(shotDC, w_scaled, h_scaled) scaledDC.SelectObject(bmp_scaled) scaledDC.StretchBlt((0,0), (w_scaled, h_scaled), shotDC, (0,0), (w, h), raster) else: bmp_scaled = bmp scaledDC = shotDC # Get screenshot bitmap into opencv image file_path = 'tmp.bmp' bmp_scaled.SaveBitmapFile(scaledDC, file_path) ##why is a DC needed? ################################################################### image_temp = cv.imread(file_path) os.remove(file_path) return cv.cvtColor(image_temp, cv.COLOR_BGRA2BGR)
def get_rect_size_client() -> Tuple[int, int]: """Returns the resolution of the game window""" rect = win32gui.GetClientRect(Window.id) return rect[2] - rect[0], rect[3] - rect[1]
from joy import update_controller_positions # inputhandler.watch_controller() model = get_large_cnn_model() hwnd = win32gui.FindWindow(None, 'AC2 ') frame_zero = time.time() all_states = [] all_training_data = [] z1 = 0 z2 = 0 if hwnd != 0: left, top, right, bot = win32gui.GetWindowRect(hwnd) w = right - left h = bot - top x, y, x1, y1 = win32gui.GetClientRect(hwnd) x, y = win32gui.ClientToScreen(hwnd, (x, y)) while True: while z1 < 1000: this_frame_time = time.time() # start time of the loop im = pyautogui.screenshot(region=(x, y, x1, y1)) # im = im.convert('L') # img = Image.fromarray(np.asarray(im), 'L') # img = img.resize(size=(256, 144)) img = im.resize(size=(256, 144)) # width, height = img.size # img.show() # Setting the points for cropped image # Vleft = width - (width * 0.9) # top = height - (height * 0.75) # right = width * 0.9
def _reset(self) -> bool: if dpi_detection: ctypes.windll.user32.SetThreadDpiAwarenessContext(-3) intermittent_log( logger, f"Resetting {self}", frequency=500, level=logging.INFO, negative_level=logging.DEBUG, caller_extra_id=( self.hwnd, self.window_title, self.executable, self.foreground_window_pid, self.process.pid if self.process else None, ), ) self.ready = False self.last_reset = time.time() self.monitors = _get_monitors() if not self.hwnd or not win32gui.IsWindow(self.hwnd): if self.window_title or self.executable: intermittent_log( logger, f"HWND invalid - looking for window matching window_title={self.window_title}, executable={self.executable}", frequency=1500, level=logging.INFO, negative_level=logging.DEBUG, caller_extra_id=(self.hwnd, self.window_title, self.executable), ) try: self.hwnd, self.process = get_hwnd(self.window_title, self.executable) except ProcessNotFoundError as e: logger.warning(f"Could not find window: {e}") self.hwnd, self.process = None, None return False elif self.foreground_window_pid: intermittent_log( logger, f"HWND invalid - looking for matching foreground window with PID={self.foreground_window_pid}", frequency=1500, level=logging.INFO, negative_level=logging.DEBUG, caller_extra_id=(self.foreground_window_pid, ), ) foreground_hwnd = win32gui.GetForegroundWindow() _, foreground_process_id = win32process.GetWindowThreadProcessId( foreground_hwnd) if foreground_process_id == self.foreground_window_pid: logger.info( f"Found foreground HWND matching PID: {foreground_hwnd}" ) self.hwnd = foreground_hwnd else: intermittent_log( logger, f"Could not find foreground window matching PID", frequency=1500, level=logging.INFO, negative_level=logging.DEBUG, caller_extra_id=(self.foreground_window_pid, ), ) self.hwnd = False return False if self.hwnd: self.style = win32api.GetWindowLong(self.hwnd, GWL_STYLE) logger.info(f"Got GWL_STYLE={self.style:08x}") self.ex_style = win32api.GetWindowLong(self.hwnd, GWL_EXSTYLE) logger.info(f"Got GWL_EXSTYLE={self.ex_style:08x}") self.win_rect = Rect(*win32gui.GetWindowRect(self.hwnd)) logger.info(f"Got WindowRect={self.win_rect}") self.client_rect = Rect(*win32gui.GetClientRect(self.hwnd)) logger.info(f"Got ClientRect={self.client_rect}") try: self.true_rect = Rect.from_RECT( DwmGetWindowAttribute(self.hwnd)) logger.info(f"Got true_rect={self.true_rect}") except Exception as e: logger.warning( f"Failed to get true_rect (DwmGetWindowAttribute): {e} - using GetWindowRect" ) self.true_rect = self.win_rect self.window_info = GetWindowInfo(self.hwnd) logger.info(f"Got WindowInfo={self.window_info}") self.foreground = False if not self.style & WS_MINIMIZE: center = self.win_rect.center if center: logger.info(f"Looking for monitor containing {center}") self.monitor = _get_monitor_containing( center, self.monitors) logger.info(f"Got monitor={self.monitor}") if self.monitor: self.foreground = True self.fullscreen = bool(self.ex_style & WS_EX_TOPMOST) self.borderless = bool(not self.style & WS_BORDER) if self.fullscreen or self.borderless: self.maximised = True else: self.maximised = bool(self.style & WS_MAXIMIZE) if self.foreground: self.crop = self._make_crop() logger.info(f"Got crop: {self.crop}") else: # no window to track - just use first monitor self.monitor = self.monitors[0] self.foreground = True self.fullscreen = True self.borderless = True self.maximised = True self.crop = None self.source = self._make_source() if self.foreground: monitor_center = self.monitor.center dll.deinit() logger.info( f"Trying to get monitor capture for center={monitor_center}") if dll.init(int(monitor_center[0]), int(monitor_center[1])): logger.warning("ScreenCapture.dll failed to init") return False bufaddr = dll.capture() if not bufaddr: logger.warning( "ScreenCapture.dll capture failed to return image data") return False buffsize = dll.get_height() * dll.get_width() * 4 d11buf = PyMemoryView_FromMemory(bufaddr, buffsize, PyBUF_READ) self.img = np.ndarray((dll.get_height(), dll.get_width(), 4), np.uint8, d11buf, order="C") logger.info("Done resetting DirectXCapture") self.ready = True return True else: self.ready = True return True
def GetClientRect(me): if user32: return (win32gui.GetClientRect(me.h)) elif X: return (me.GetWindowRect()) return ((0, 0, 0, 0))
def _CreateChildWindow(self, prev): # Creates the list view window. assert self.hwnd_child is None, "already have a window" assert self.cur_foldersettings is not None, "no settings" style = (win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER | commctrl.LVS_SHAREIMAGELISTS | commctrl.LVS_EDITLABELS) view_mode, view_flags = self.cur_foldersettings if view_mode == shellcon.FVM_ICON: style |= commctrl.LVS_ICON | commctrl.LVS_AUTOARRANGE elif view_mode == shellcon.FVM_SMALLICON: style |= commctrl.LVS_SMALLICON | commctrl.LVS_AUTOARRANGE elif view_mode == shellcon.FVM_LIST: style |= commctrl.LVS_LIST | commctrl.LVS_AUTOARRANGE elif view_mode == shellcon.FVM_DETAILS: style |= commctrl.LVS_REPORT | commctrl.LVS_AUTOARRANGE else: # XP 'thumbnails' etc view_mode = shellcon.FVM_DETAILS # Default to 'report' style |= commctrl.LVS_REPORT | commctrl.LVS_AUTOARRANGE for f_flag, l_flag in [ (shellcon.FWF_SINGLESEL, commctrl.LVS_SINGLESEL), (shellcon.FWF_ALIGNLEFT, commctrl.LVS_ALIGNLEFT), (shellcon.FWF_SHOWSELALWAYS, commctrl.LVS_SHOWSELALWAYS), ]: if view_flags & f_flag: style |= l_flag self.hwnd_child = win32gui.CreateWindowEx( win32con.WS_EX_CLIENTEDGE, "SysListView32", None, style, 0, 0, 0, 0, self.hwnd, 1000, 0, None, ) cr = win32gui.GetClientRect(self.hwnd) win32gui.MoveWindow(self.hwnd_child, 0, 0, cr[2] - cr[0], cr[3] - cr[1], True) # Setup the columns for the view. lvc, extras = win32gui_struct.PackLVCOLUMN(fmt=commctrl.LVCFMT_LEFT, subItem=1, text="Name", cx=300) win32gui.SendMessage(self.hwnd_child, commctrl.LVM_INSERTCOLUMN, 0, lvc) lvc, extras = win32gui_struct.PackLVCOLUMN(fmt=commctrl.LVCFMT_RIGHT, subItem=1, text="Exists", cx=50) win32gui.SendMessage(self.hwnd_child, commctrl.LVM_INSERTCOLUMN, 1, lvc) # and fill it with the content self.Refresh()
def get_window_bounds(name): win = win32gui.FindWindow(None, name) if win == 0: return None rect = win32gui.GetClientRect(win) origin = win32gui.ClientToScreen(win, (0,0)) return (rect[0] + origin[0], rect[1] + origin[1], rect[2] + origin[0], rect[3] + origin[1])
def get_client_size(self): left, top, right, bot = win32gui.GetClientRect(self.window) return right - left, bot - top
def get_window_size(name): win = win32gui.FindWindow(None, name) if win == 0: return None return win32gui.GetClientRect(win)
def __init__(self, hwnd, scaling): # 获取游戏窗口坐标 self.hwnd = hwnd self.left, self.top, self.right, self.bottom = win32gui.GetWindowRect( self.hwnd) self.client_rect = win32gui.GetClientRect(self.hwnd) self.width = self.client_rect[2] self.height = self.client_rect[3] # 获取游戏画面坐标 self.left, self.top = win32gui.ClientToScreen(self.hwnd, (0, 0)) self.right, self.bottom = win32gui.ClientToScreen( self.hwnd, (self.width, self.height)) # 缩放后的游戏窗口坐标 self.ltrb = list( map(lambda x: x * scaling, [self.left, self.top, self.right, self.bottom])) self.scaling_width = self.width * scaling self.scaling_height = self.height * scaling # 挑战按钮坐标 self.chllg_btn = (round(self.left + self.width * 0.695), round(self.top + self.height * 0.67), round(self.left + self.width * 0.785), round(self.top + self.height * 0.73)) # 开始战斗按钮坐标 self.fght_btn = (round(self.left + self.width * 0.75), round(self.top + self.height * 0.82), round(self.left + self.width * 0.87), round(self.top + self.height * 0.88)) # 退出战斗按钮采样坐标 self.exit_btn = (round(self.ltrb[0] + self.scaling_width * 0.014), round(self.ltrb[1] + self.scaling_height * 0.0245), round(self.ltrb[0] + self.scaling_width * 0.0415), round(self.ltrb[1] + self.scaling_height * 0.074)) # 退出战斗按钮hash self.exit_btn_hash = '1ff83ffc3ffe3ffe007e001f001f019f079e1ffe7fff7ffe1ff8078001800000' # 结算判定区域采样坐标 self.settle_area = (round(self.ltrb[0] + self.scaling_width * 0.42), round(self.ltrb[1] + self.scaling_height * 0.82), round(self.ltrb[0] + self.scaling_width * 0.58), round(self.ltrb[1] + self.scaling_height * 0.86)) # 结算判定区域hash self.settle_area_hash = '4f3f672f600fa01fb03ff03ff07df874f171d170c170c970c320c020c000c000' # 单刷界面判定采样坐标 self.single_intf = (round(self.ltrb[0] + self.scaling_width * 0.45), round(self.ltrb[1] + self.scaling_height * 0.1), round(self.ltrb[0] + self.scaling_width * 0.58), round(self.ltrb[1] + self.scaling_height * 0.18)) self.single_hash = '000000000000000000186e1836387ebc7ebc7eb86ed897fc0000ffffffffffff' # 组队界面判定采样坐标# self.form_team_intf = (round(self.ltrb[0] + self.scaling_width * 0.12), round(self.ltrb[1] + self.scaling_height * 0.8), round(self.ltrb[0] + self.scaling_width * 0.24), round(self.ltrb[1] + self.scaling_height * 0.88)) # 组队界面判定hash self.form_team_hash = '7ffeffffffffffffcd33cd33c823c923cd93c901e577ffffffff7ffe00000000' # 组队栏位1采样坐标 self.form_team1 = (round(self.ltrb[0] + self.scaling_width * 0.2), round(self.ltrb[1] + self.scaling_height * 0.4), round(self.ltrb[0] + self.scaling_width * 0.28), round(self.ltrb[1] + self.scaling_height * 0.53)) # 组队栏位2采样坐标 self.form_team2 = (round(self.ltrb[0] + self.scaling_width * 0.46), round(self.ltrb[1] + self.scaling_height * 0.4), round(self.ltrb[0] + self.scaling_width * 0.54), round(self.ltrb[1] + self.scaling_height * 0.53)) # 组队栏位3采样坐标 self.form_team3 = (round(self.ltrb[0] + self.scaling_width * 0.76), round(self.ltrb[1] + self.scaling_height * 0.4), round(self.ltrb[0] + self.scaling_width * 0.84), round(self.ltrb[1] + self.scaling_height * 0.53)) # 点击屏幕继续字样采样坐标 self.notice_area = (round(self.ltrb[2] * 0.40), round(self.ltrb[3] * 0.90), round(self.ltrb[2] * 0.60), round(self.ltrb[3] * 0.97)) # 结算点击区域坐标 self.blank_area = (round(self.left + self.width * 0.86), round(self.top + self.height * 0.23), round(self.left + self.width * 0.95), round(self.top + self.height * 0.7)) # 组队栏位为空时hash self.form_team_blank_hash = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' # 悬赏界面采样坐标 self.offer_intf = (round(self.ltrb[0] + self.scaling_width * 0.4), round(self.ltrb[1] + self.scaling_height * 0.2), round(self.ltrb[0] + self.scaling_width * 0.6), round(self.ltrb[1] + self.scaling_height * 0.28)) # 悬赏界面hash self.offer_hash = 'ffffffffffff3fff35fde004200020000004040420100064247037f7ffffffff' # 悬赏接受按钮坐标 self.accept = (round(self.left + self.width * 0.66), round(self.top + self.height * 0.6)) # 悬赏拒绝按钮坐标 self.denied = (round(self.left + self.width * 0.66), round(self.top + self.height * 0.74)) # 状态初始化 self._running = 1
def _get_dimensions(self): x1, y1, x2, y2 = win32gui.GetClientRect(self._handle) x1, y1 = win32gui.ClientToScreen(self._handle, (x1, y1)) x2, y2 = win32gui.ClientToScreen(self._handle, (x2 - x1, y2 - y1)) return x1, y1, x2, y2
def get_client_rect(hwnd): l, t, r, b = win32gui.GetClientRect(hwnd) w = r - l h = b - t return (l, t, w, h)
def autoSweep(): hWnd = win32gui.FindWindow('Minesweeper', None) if hWnd == win32con.NULL: print 'Failed to find the Minesweeper\'s window.' return 1 ThreadID, ProcessID = win32process.GetWindowThreadProcessId(hWnd) hProcess = OpenProcess(PROCESS_ALL_ACCESS, False, ProcessID) if hProcess == win32con.NULL: print 'Failed to open the Minesweeper\'s process.' return 1 hSnapshot = c_void_p(0) me32 = MODULEENTRY32() me32.dwSize = sizeof(MODULEENTRY32) hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID) ret = Module32First(hSnapshot, pointer(me32)) if ret == False: CloseHandle(hSnapshot) print 'Failed to enumerate the module' return 1 while ret: if cmp(me32.szModule.lower(), 'minesweeper.exe') == 0: mineBaseAddr = int(me32.modBaseAddr) ret = Module32Next(hSnapshot, pointer(me32)) CloseHandle(hSnapshot) buffer = c_void_p(0) dwDate = c_void_p(0) topBaseAddr = mineBaseAddr + 0x868B4 MineInfo = {'count': 0, 'row': 0, 'column': 0} try: ReadProcessMemory(hProcess, topBaseAddr, pointer(buffer), 4, win32con.NULL) ReadProcessMemory(hProcess, buffer.value + 0x10, pointer(buffer), 4, win32con.NULL) ReadProcessMemory(hProcess, buffer.value + 0x04, pointer(dwDate), 4, win32con.NULL) MineInfo['count'] = dwDate.value ReadProcessMemory(hProcess, buffer.value + 0x08, pointer(dwDate), 4, win32con.NULL) MineInfo['row'] = dwDate.value ReadProcessMemory(hProcess, buffer.value + 0x0C, pointer(dwDate), 4, win32con.NULL) MineInfo['column'] = dwDate.value except: print 'Failed to read the Minesweeper\'s memory date.' return 1 win32gui.SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE) cleft, ctop, cright, cbottom = win32gui.GetClientRect(hWnd) if cright <= 0 or cbottom <= 0: print 'Failed to get the rectangle of th Minesweeper\'s window.' return 1 x, y = win32gui.ClientToScreen(hWnd, (cleft, ctop)) edge = cright / (MineInfo['column'] + 4) + 1 originX = edge * 2 + edge / 2 + x originY = (cbottom - MineInfo['row'] * edge) / 2 + edge / 2 + y win32api.SetCursorPos((originX, originY)) time.sleep(0.05) win32api.mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) win32api.mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) time.sleep(1) ReadProcessMemory(hProcess, buffer.value + 0x44, pointer(buffer), 4, win32con.NULL) ReadProcessMemory(hProcess, buffer.value + 0x0C, pointer(buffer), 4, win32con.NULL) buffer2 = c_void_p(0) dwDate2 = c_void_p(0) bFlag = [[0 for col in range(MineInfo['row'])] for row in range(MineInfo['column'])] for i in range(0, MineInfo['column']): ReadProcessMemory(hProcess, buffer.value + 4 * i, pointer(buffer2), 4, win32con.NULL) ReadProcessMemory(hProcess, buffer2.value + 0x0C, pointer(buffer2), 4, win32con.NULL) for j in range(0, MineInfo['row']): ReadProcessMemory(hProcess, buffer2.value + j, pointer(dwDate2), 1, win32con.NULL) if dwDate2.value == None: bFlag[i][j] = 0 else: bFlag[i][j] = dwDate2.value print i, j, bFlag[i][j] CloseHandle(hProcess) Count = 0 for i in range(0, MineInfo['row']): for j in range(0, MineInfo['column']): if win32gui.FindWindow('Minesweeper', None) != win32con.NULL: win32api.SetCursorPos((originX + j * edge, originY + i * edge)) if bFlag[j][i] == 0: win32api.mouse_event( MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) Count += 1 else: if Count == (MineInfo['row'] * MineInfo['column'] - MineInfo['count']): break win32api.mouse_event( MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0) time.sleep(.015) else: print 'Failed to find the Minesweeper\'s window.' return 1 print hWnd win32gui.SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE) return 0
def procssImage(pos_i_array): def window_enumeration_handler(hwnd, window_hwnds): if win32gui.GetClassName(hwnd) == "UnrealWindow": window_hwnds.append(hwnd) def calc_centroid(img): """Get the centroid and area of green in the image""" hue_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) low_range = np.array([165, 145, 30]) high_range = np.array([180, 200, 58]) th = cv2.inRange(hue_image, low_range, high_range) # cv2.imshow("img", img) # cv2.waitKey(1) M = cv2.moments(th, binaryImage=True) if M["m00"] >= min_prop * width * height: cx = int(M["m10"] / M["m00"]) cy = int(M["m01"] / M["m00"]) return [cx, cy, int(M["m00"])] else: return [-1, -1, -1] # parameters width = 720 height = 405 # channel = 4 min_prop = 0.000001 time.sleep(5) window_hwnds = [] win32gui.EnumWindows(window_enumeration_handler, window_hwnds) if len(window_hwnds) > 0: print("window_hwnds: {}".format(window_hwnds)) window_hwnds.sort() hWnd = window_hwnds[0] print("hWnd: {}".format(hWnd)) #hWnd = win32gui.FindWindow("UnrealWindow", None) left, top, right, bot = win32gui.GetClientRect(hWnd) windows_width = right - left windows_height = bot - top if hWnd and windows_width != width: hWnd = window_hwnds.sort(reverse=True) hWnd = window_hwnds[0] left, top, right, bot = win32gui.GetClientRect(hWnd) windows_width = right - left windows_height = bot - top print("Not the desired window.") if hWnd and windows_width == 0 and windows_height == 0: print("The UE4 window cannot be in minimum mode.") sys.exit(1) # 返回句柄窗口的设备环境,覆盖整个窗口,包括非客户区,标题栏,菜单,边框 hWndDC = win32gui.GetWindowDC(hWnd) # 创建设备描述表 mfcDC = win32ui.CreateDCFromHandle(hWndDC) # 创建内存设备描述表 saveDC = mfcDC.CreateCompatibleDC() # 创建位图对象准备保存图片 saveBitMap = win32ui.CreateBitmap() # 为bitmap开辟存储空间 saveBitMap.CreateCompatibleBitmap(mfcDC, windows_width, windows_height) while True: #这里处理图像,并获取到速度控制指令 saveDC.SelectObject(saveBitMap) # 0-保存整个窗口,1-只保存客户区。如果PrintWindow成功函数返回值为1 _ = windll.user32.PrintWindow(hWnd, saveDC.GetSafeHdc(), 1) signedIntsArray = saveBitMap.GetBitmapBits(True) img_rgba = np.frombuffer(signedIntsArray, dtype='uint8') img_rgba.shape = (windows_height, windows_width, 4) img_bgr = cv2.cvtColor(img_rgba, cv2.COLOR_RGBA2RGB) img_bgr = cv2.resize(img_bgr, (width, height)) pos_i_array[0], pos_i_array[1], pos_i_array[2] = calc_centroid(img_bgr)
import win32api, win32gui, win32con import sys, os import time #label = 'BlueStacks App Player' #蓝叠模拟器 label = 'Pisces' #pc客户端标题且无子句柄 #win32gui.GetClientRect(hld) #获取client的窗口大小 #win32gui.ClientToScreen(hld,(0,0)) #将client的(0,0)坐标转为屏幕坐标 hld = win32gui.FindWindow(None, label) if hld > 0 and label == 'BlueStacks App Player': dlg = win32gui.FindWindowEx(hld, 0, None, 'HOSTWND') #获取hld下第一个为edit控件的句柄 dlg = win32gui.FindWindowEx(dlg, 0, None, None) #获取hld下第一个为edit控件的句柄 dlg = win32gui.FindWindowEx(dlg, 0, None, None) position = win32gui.GetWindowRect(dlg) #print win32gui.GetWindowRect(dlg) elif label == 'Pisces': if hld <= 0: os.system("C:\\bin\\StartPisces.bat") #client's path time.sleep(5) hld = win32gui.FindWindow(None, label) win32gui.SetForegroundWindow(hld) dlg = win32gui.GetClientRect(hld) #获取client的窗口大小 position = win32gui.ClientToScreen(hld, (0, 0)) #将client的(0,0)坐标转为屏幕坐标 fp = open("E:\\pisces_af\\ScriptConfig.ini", 'w') fp.write(str(position)) fp.close() sys.exit(0)