# TILE PARAMS # tile dimensions are: # - 17 height (including BOTH borders (i.e. 1px each side)) # - 32 width (including half of side borders (i.e. 1px each side) BORDERCOLOR = (121, 93, 40) OFFMAPCOLOR = (65, 28, 4) WATER = (32, 36, 255) BLACK = (0, 0, 0) GROUNDLIGHT = (154, 134, 69) GROUNDDARK = (142, 117, 56) TILE_HEIGHT = 17 TILE_WIDTH = 32 # DESKTOP SETTINGS i_desktop_window_id = win32gui.GetDesktopWindow() i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id) red = win32api.RGB(255, 0, 0) # WINDOW, MENU AND SCROLLBAR window = None mn = None scrollbar = None scroll_left = None scroll_right = None scroll_up = None scroll_down = None # finds suitable starting position # returns position and bool saying if position contains slopes def find_starting_point(window, brain, current_position):
import win32gui import win32ui import win32con import win32api # grab a handle to the main desktop window hdesktop = win32gui.GetDesktopWindow() # determine the size of all monitors in pixels width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) top = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) # create a device context desktop_dc = win32gui.GetWindowDC(hdesktop) img_dc = win32ui.CreateDCFromHandle(desktop_dc) # create a memory based device context mem_dc = img_dc.CreateCompatibleDC() # create a bitmap object screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, width, height) mem_dc.SelectObject(screenshot) # copy the screen into our memory device context mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) # save the bitmap to a file screenshot.SaveBitmapFile(mem_dc, 'c:\\WINDOWS\\Temp\\screenshot.bmp')
# 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) # NOTE: seems like win32 libs are set to use # Full HD 1920 * 1080 monitor resolution, # so if you using 4K 3840 * 2160 then you # need to scale w and h values: w_scale = 3840 // 1920 h_scale = 2160 // 1080 w = (right - left) * w_scale h = (bot - top) * h_scale 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(), 1) # result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0) print(result) bmpinfo = saveBitMap.GetInfo()
# encontra hwnd do pangya pangya = [(hwnd, title) for hwnd, title in winlist if 'pangya fresh up' in title.lower()] pangya = pangya[0] pangya_hwnd = pangya[0] # pega boundaries da janela, calcula dimensões l, t, r, b = win32gui.GetWindowRect(pangya_hwnd) width = r-l height = b-t # hardcoding legal para tirar as bordas do windows border_size = 8 top_border = 30 width -= border_size*2 # direita, esquerda height -= top_border+border_size # top, bottom # magic hDC = win32gui.GetWindowDC(pangya_hwnd) myDC = win32ui.CreateDCFromHandle(hDC) newDC = myDC.CreateCompatibleDC() myBitMap = win32ui.CreateBitmap() myBitMap.CreateCompatibleBitmap(myDC, width, height) newDC.SelectObject(myBitMap) newDC.BitBlt((0,0),(width,height), myDC,(border_size,top_border),win32con.SRCCOPY) myBitMap.Paint(newDC) myBitMap.SaveBitmapFile(newDC,'10_xd_1.bmp') process_img('10_xd_1.bmp')
def init(self): win32gui.EnumWindows(self.getWindows, None) self.wDC = win32gui.GetWindowDC(self.hwnd_game) win32gui.SetForegroundWindow(self.hwnd_game) self.focus()
from PIL import ImageGrab from pytesseract import * import aircv import os import random hWin = win32gui.FindWindow(None, '雷电模拟器') ch = win32gui.FindWindowEx(hWin, 0, None, 'TheRender') b = win32ui.CreateWindowFromHandle(ch) x = 0 y = 38 rect = win32gui.GetWindowRect(hWin) w = rect[2] - rect[0] - 38 h = rect[3] - rect[1] - 38 hwndDC = win32gui.GetWindowDC(hWin) # 根据窗口句柄获取窗口的设备上下文DC(Divice Context) mfcDC = win32ui.CreateDCFromHandle(hwndDC) # 根据窗口的DC获取mfcDC saveDC = mfcDC.CreateCompatibleDC() # mfcDC创建可兼容的DC saveBitMap = win32ui.CreateBitmap() # 创建bigmap准备保存图片 saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) # 为bitmap开辟空间 state_map = [ ['battle_complete', 'touch.png'], ['get_new_pm', 'state_newpm.png'], ['get_pm', 'state_getpm.png'], ['battle_pre', 'do_attack.png'], ['sel_support', 'sel_support.png'], ['sel_team', 'sel_team.png'], ['do_attack_pre', 'team_attack.png'], ['battle_map', 'auto_walk.png'],
def main(): # Define name for the window class_name = "Win32Window0" title_name = "阴阳师-网易游戏" # Find the hwnd of the window hwnd = win32gui.FindWindow(class_name, title_name) # Get the input for total running time print("运行时间:", end="") total_time = int(input()) start_time = time.time() # Run the main function while time.time() - start_time < total_time: # Set the program to forground #win32gui.SetForegroundWindow(hwnd) left, top, right, bottom = win32gui.GetClientRect(hwnd) # Calculat the size of the window width = right - left height = bottom - top # Create DCs hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() # Create Bit Map saveBitMap = win32ui.CreateBitmap() saveBitMap.CreateCompatibleBitmap(mfcDC, width, height) saveDC.SelectObject(saveBitMap) # Save the screenshot saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) # Save to image im = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) screen = np.array(im) # Remove DCs win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC) # Search white pixels #for i in range(470): # for j in range(850): # #if screen[i][j][0] == 255 and screen[i][j][1] == 255 and screen[i][j][2] == 255: # #if screen[i][j][0] == 0 and screen[i][j][1] == 0 and screen[i][j][2] == 0: # if screen[i][j][0] == 150 and screen[i][j][1] == 141 and screen[i][j][2] == 131: # print(i, j) # Click if the pixel is white if screen[468][148][0] == 255 and screen[468][148][ 1] == 255 and screen[468][148][2] == 255: x, y = rand_next(width, height) # Click the start button if in party elif screen[395][600][0] == 150 and screen[395][600][ 1] == 141 and screen[395][600][2] == 131: x, y = rand_start(width, height) else: # Sleep for random time time.sleep(1.5 + random.random() * 0.8) continue l_param = win32api.MAKELONG(x, y) win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 0, l_param) #win32api.SendMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, l_param) win32api.SendMessage(hwnd, win32con.WM_LBUTTONDOWN, 0, l_param) time.sleep(0.03 + random.random() * 0.02) win32api.SendMessage(hwnd, win32con.WM_LBUTTONUP, 0, l_param) # Sleep for random time time.sleep(1.5 + random.random() * 0.8)
def draw(x, y): win = win32gui.GetForegroundWindow() dc = win32gui.GetWindowDC(win) win32gui.SetPixel(dc, x, y, RGB(255, 255, 255)) win32gui.ReleaseDC(win, dc)
def get_color(x, y, dc=win32gui.GetWindowDC(win32gui.GetDesktopWindow())): #img_11 = ImageGrab.grab(bbox=(x, y, x + 1, y + 1)) hdc_color = win32gui.GetPixel(dc, x, y) #return img_11.getpixel((0, 0)) return hdc_color
while (1): try: handle = win32gui.FindWindow(None, Str) print('Find the Game!') break except: print('The program don' 't found the Game!') sleep(1) # handle = win32gui.GetDesktopWindow() #handle = 2361912 handle # win32gui.FindWindow(Str) # win32gui.FindWindow(None,530628) dc = win32gui.GetWindowDC(handle) # dc = 0 dc # get_color(0,0) # win32gui.GetPixel(dc,xy[0],xy[1]) from time import sleep #time.sleep(1) def stop_0(ch='g'): # ch = 'a' break0 = 0 ch = ch.upper()
def getDCAndBitMap(saveBmpFilename=None, rect=None): """ Returns a (DC, PyCBitmap). On the returned DC ("device context"), you *must* call aDC.DeleteDC(). On the returned PyCBitmap, you *must* call win32gui.DeleteObject(aPyCBitmap.GetHandle()). If C{saveBmpFilename} is provided, a .bmp will be saved to the specified filename. This does not require PIL. The .bmp file will have the same bit-depth as the screen; it is not guaranteed to be 32-bit. If you provide this argument, you still must clean up the returned objects, as mentioned. If C{rect} is not C{None}, instead of capturing the entire virtual screen, only the region inside the rect will be captured. C{rect} is a tuple of ( the x-coordinate of the upper-left corner of the virtual screen, the y-coordinate of the upper-left corner of the virtual screen, the x-coordinate of the lower-right corner of the virtual screen, the y-coordinate of the lower-right corner of the virtual screen ) Note that both x and y coordinates may be negative; the (0, 0) origin is determined by the top-left corner of the main display (not necessarily Display 1). Raises L{GrabFailed} if unable to take a screenshot (e.g. due to locked workstation, no display, or active UAC elevation screen). Raises L{ValueError} if C{rect}'s computed width or height is zero or negative, or if rect contains nonsense. """ if rect is None: try: rect = getVirtualScreenRect() except RectFailed as e: raise GrabFailed("Error during getVirtualScreenRect: " + str(e)) # rect is already checked else: checkRect(rect) left, top, right, bottom = rect width = right - left height = bottom - top hwndDesktop = win32gui.GetDesktopWindow() # Retrieve the device context (DC) for the entire virtual screen. hwndDevice = win32gui.GetWindowDC(hwndDesktop) ##print("device", hwndDevice) assert isinstance(hwndDevice, int), hwndDevice mfcDC = win32ui.CreateDCFromHandle(hwndDevice) try: saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() # Above line is assumed to never raise an exception. try: try: saveBitMap.CreateCompatibleBitmap(mfcDC, width, height) except (win32ui.error, OverflowError) as e: raise GrabFailed( "Could not CreateCompatibleBitmap(" "mfcDC, %r, %r) - perhaps too big? Error was: %s" % (width, height, e)) saveDC.SelectObject(saveBitMap) try: saveDC.BitBlt((0, 0), (width, height), mfcDC, (left, top), win32con.SRCCOPY) except win32ui.error as e: raise GrabFailed( "Error during BitBlt. " "Possible reasons: locked workstation, no display, " "or an active UAC elevation screen. Error was: " + str(e)) if saveBmpFilename is not None: saveBitMap.SaveBitmapFile(saveDC, saveBmpFilename) except: deleteDCAndBitMap(saveDC, saveBitMap) # Let's just hope the above line doesn't raise an exception # (or it will mask the previous exception) raise finally: mfcDC.DeleteDC() return saveDC, saveBitMap
def get_screen(in_size=None, color="BGR"): logger.debug("edcm.screen.get_screen(screen_size=%s)" % in_size) screen_size = get_elite_size() display_size = get_screen_size() logger.debug("%s %s %s %s" % (in_size['top'], in_size['left'], in_size['height'], in_size['width'])) # if window is full screen if display_size['width'] > screen_size['width']: # resolution has been scaled logger.info("resolution has been scaled: display %s x %s > screen %s x %s" % (display_size['width'], display_size['height'], screen_size['width'], screen_size['height'])) scalar_x = display_size['width']/screen_size['width'] scalar_y = display_size['height']/screen_size['height'] capture = { 'top': round(int(in_size['top'] * scalar_y)), 'left': round(int(in_size['left'] * scalar_x)), 'height': round(int(in_size['height'] * scalar_y)), 'width': round(int(in_size['width'] * scalar_x))} logger.debug("capture[top] = in_size[top] * scalar_x : %s = %s * %s" % (capture['top'], in_size['top'], scalar_x)) logger.debug("capture[] = in_size[width] * scalar_x : %s = %s * %s" % (capture['width'], in_size['width'], scalar_x)) logger.debug("capture[width] = in_size[width] * scalar_x : %s = %s * %s" % (capture['width'], in_size['width'], scalar_x)) logger.debug("capture[width] = in_size[width] * scalar_x : %s = %s * %s" % (capture['width'], in_size['width'], scalar_x)) else: capture = in_size logger.debug("%s %s %s %s" % (capture['top'], capture['left'], capture['height'], capture['width'])) # get int handle to main desktop hwin = win32gui.GetDesktopWindow() # create device contexts hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) # create PyCDC Object from int handle memdc = srcdc.CreateCompatibleDC() # create a Memory Device Context from source Device Context # create a bitmap screenshot screenshot = win32ui.CreateBitmap() # create bit map object screenshot.CreateCompatibleBitmap(srcdc, int(screen_size['width']), int(screen_size['height'])) # create bitmap memdc.SelectObject(screenshot) # copy screen to memory device context memdc.BitBlt((0, 0), (capture['width'], capture['height']), srcdc, (capture['left'], capture['top']), win32con.SRCCOPY) # copies logger.debug( "get_screen: memdc.BitBlt((0,0)," " (capture['width']= %s, capture['height']= %s, capture['left']= %s, capture['top']= %s)," " win32con.SRCCOPY)" % (capture['width'], capture['height'], capture['left'], capture['top'])) # create Numpy Image Array bitmap_data = screenshot.GetBitmapBits(True) b_info = screenshot.GetInfo() img = np.fromstring(bitmap_data, dtype=np.uint8) img.shape = (b_info['bmHeight'], b_info['bmWidth'], 4) # clear resources srcdc.DeleteDC() memdc.DeleteDC() win32gui.ReleaseDC(hwin, hwindc) win32gui.DeleteObject(screenshot.GetHandle()) if color.upper() == 'RGB': color = cv2.COLOR_BGRA2RGB elif color.upper() == 'GRAY': color = cv2.COLOR_BGRA2GRAY elif color.upper() == 'BGR': color = cv2.COLOR_BGRA2BGR return cv2.cvtColor(img, color)
def get_screen(self): '''Make Screenshot of running window. Returns (Error, Imagesize, Image) Error - Boolean Image - PIL-Image object Imagesize - Tuple(x,y) size of the image in form (Width,Height) windowlocation - Tuple(x,y) location of the upper left window corner ''' try: hwnd = win32gui.FindWindow(None, self.wndname) left, top, right, bot = win32gui.GetWindowRect(hwnd) cleft, ctop, cright, cbot = win32gui.GetClientRect(hwnd) w = right - left h = bot - top cw = cright - cleft ch = cbot - ctop hwndDC = win32gui.GetWindowDC(hwnd) mfcDC = win32ui.CreateDCFromHandle(hwndDC) saveDC = mfcDC.CreateCompatibleDC() saveBitMap = win32ui.CreateBitmap() if self.onlyarea: saveBitMap.CreateCompatibleBitmap(mfcDC, cw, ch) else: saveBitMap.CreateCompatibleBitmap(mfcDC, w, h) saveDC.SelectObject(saveBitMap) #whole window or just the client area. if self.onlyarea: result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1) else: result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 0) bmpinfo = saveBitMap.GetInfo() bmpstr = saveBitMap.GetBitmapBits(True) self.image = Image.frombuffer( 'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) if self.dpiaware: self.image = self.image.crop( (0, 0, self.real_wndsize[0], self.real_wndsize[1])) win32gui.DeleteObject(saveBitMap.GetHandle()) saveDC.DeleteDC() mfcDC.DeleteDC() win32gui.ReleaseDC(hwnd, hwndDC) self.imsize = (self.image.width, self.image.height) self.wndloc = (left, top) self.wndsize = (w, h) except: result = 0 print("Error while getting Screen.") finally: if result == 1: #PrintWindow succeeded, return error=False return False, self.image, self.imsize, self.wndloc, self.wndsize else: #PrintWindow failed, return error=True return True, None, (0, 0), (0, 0), (640, 480)