def __init__(self, dest_widget, src_hdl=0x00010010): """Crée un stream.""" if sys.platform == 'win32': self._destWidget = dest_widget self._src_hdl = src_hdl self.src_window_dc = win32gui.GetDC(self._src_hdl) # Récupère l'handle et le DC du dest_widget self._dest_hdl = dest_widget.winfo_id() self.dest_window_dc = win32gui.GetDC(self._dest_hdl) # Crée un DC compatible pour la sauvegarde self.mem_dc = win32gui.CreateCompatibleDC(self.dest_window_dc) if self.mem_dc is None: log.add("Échec de la création du compatibleDC.") return self.dest_rect_dc = win32gui.GetClientRect(self._dest_hdl) self.src_rect_dc = win32gui.GetClientRect(self._src_hdl) win32gui.SetStretchBltMode(self.dest_window_dc, win.HALFTONE) self._hasToRun = False self.timer = InfiniteTimer(1 / 24, self.run) elif sys.platform == 'linux': """TODO : Lalie ?""" pass
def xiazhu(s, hwnd): time.sleep(0.5) ##win32gui.SetForegroundWindow(hwnd) windll.user32.SetCursorPos(673, 350) hdc = win32gui.GetDC(hwnd) color1 = color2 = win32gui.GetPixel(hdc, 673, 350) win32gui.ReleaseDC(hwnd, hdc) while color1 == color2 and color1 == 2787168: time.sleep(1) hdc = win32gui.GetDC(hwnd) color2 = win32gui.GetPixel(hdc, 673, 350) win32gui.ReleaseDC(hwnd, hdc)
def get_realtime_pixel(): # 실시간으로 마우스 위치의 픽셀을 출력하는 함수 prev = win32api.GetCursorPos() while True: mouse_p = win32api.GetCursorPos() if prev != mouse_p: print('Hex : ' + str( hex( win32gui.GetPixel( win32gui.GetDC(win32gui.GetDesktopWindow()), mouse_p[0], mouse_p[1]))) + ' Int : ' + str( win32gui.GetPixel( win32gui.GetDC(win32gui.GetDesktopWindow()), mouse_p[0], mouse_p[1]))) prev = mouse_p
def brain_eval(x, y): wnd = win32gui.GetForegroundWindow() dc = win32gui.GetDC(wnd) rc = win32gui.GetClientRect(wnd) c = str(board[x][y]) win32gui.ExtTextOut(dc, rc[2] - 15, 3, 0, None, c, ()) win32gui.ReleaseDC(wnd, dc)
def grab_im(): while True: cursor_current_x, cursor_current_y = 0, 0 crop_im = False win_DC = win32gui.GetDC(0) cursor_origin_x, cursor_origin_y = win32gui.GetCursorPos() full_image = ImageGrab.grab(bbox=(0, 0, win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1))) while win32api.GetAsyncKeyState(win32con.VK_CONTROL) < 0: if not crop_im: crop_im = True cursor_current_x, cursor_current_y = win32gui.GetCursorPos() win32gui.MoveToEx(win_DC, cursor_origin_x, cursor_origin_y) win32gui.LineTo(win_DC, cursor_origin_x, cursor_current_y) win32gui.MoveToEx(win_DC, cursor_origin_x, cursor_current_y) win32gui.LineTo(win_DC, cursor_current_x, cursor_current_y) win32gui.MoveToEx(win_DC, cursor_current_x, cursor_current_y) win32gui.LineTo(win_DC, cursor_current_x, cursor_origin_y) win32gui.MoveToEx(win_DC, cursor_current_x, cursor_origin_y) win32gui.LineTo(win_DC, cursor_origin_x, cursor_origin_y) if crop_im: cropped_image = full_image.crop( (min(cursor_current_x, cursor_origin_x), min(cursor_current_y, cursor_origin_y), max(cursor_current_x, cursor_origin_x), max(cursor_current_y, cursor_origin_y))) return cropped_image sleep(.01)
def prep_menu_icon(self, icon): #Couldn't get this to work with pngs, only ico # First load the icon. ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON) hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE) hdcBitmap = win32gui.CreateCompatibleDC(0) hdcScreen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y) hbmOld = win32gui.SelectObject(hdcBitmap, hbm) # Fill the background. brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) # unclear if brush needs to be feed. Best clue I can find is: # "GetSysColorBrush returns a cached brush instead of allocating a new # one." - implies no DeleteObject # draw the icon win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL) win32gui.SelectObject(hdcBitmap, hbmOld) win32gui.DeleteDC(hdcBitmap) return hbm
def ScreenShot(dpath): hwndDC = win32gui.GetDC(hwnd) memDc = win32gui.CreateCompatibleDC(hwndDC) hBmp = win32gui.CreateCompatibleBitmap(hwndDC, 800, 600) oldBmp = win32gui.SelectObject(memDc, hBmp) #win32gui.BitBlt(memDc,0,0,800,600,hwndDC,0,0,win32con.SRCCOPY); ctypes.windll.user32.PrintWindow(hwnd, memDc, 1) filename = TimeStamp() bmpname = dpath + filename + '.bmp' saveBitMap = win32ui.CreateBitmapFromHandle(hBmp) saveDC = win32ui.CreateDCFromHandle(memDc) saveBitMap.SaveBitmapFile(saveDC, bmpname) win32gui.SelectObject(memDc, oldBmp) win32gui.DeleteObject(memDc) win32gui.DeleteObject(hBmp) win32gui.ReleaseDC(hwnd, hwndDC) jpgname = bmpname[:-4]+".jpg" Image.open(bmpname).save(jpgname) SafeDelete(bmpname) screenList.append(jpgname) if len(screenList) > 300: SafeDelete(screenList[0]) del(screenList[0])
def test(exePath): import win32ui import win32gui import win32con import win32api # ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) # ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) ico_x = 32 ico_y = 32 # exePath = "c:/windows/system32/shell32.dll" large, small = win32gui.ExtractIconEx(exePath, 0) useIcon = large[0] destroyIcon = small[0] win32gui.DestroyIcon(destroyIcon) print('dd', (useIcon)) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), useIcon) savePath = "d:/test.bmp" hbmp.SaveBitmapFile(hdc, savePath)
def window_capture(hwnd): try: #f = ctypes.windll.dwmapi.DwmGetWindowAttribute f = ctypes.windll.shcore.SetProcessDpiAwareness except WindowsError: f = None if not f: exit(0) else: PROCESS_SYSTEM_DPI_AWARE = 1 f(PROCESS_SYSTEM_DPI_AWARE) l, t, r, b = win32gui.GetClientRect(hwnd) w = r - l h = b - t hwnd_client_dc = win32gui.GetDC(hwnd) img_dc = win32ui.CreateDCFromHandle(hwnd_client_dc) mem_dc = img_dc.CreateCompatibleDC() screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, w, h) mem_dc.SelectObject(screenshot) mem_dc.BitBlt((0, 0), (w, h), img_dc, (l, t), win32con.SRCCOPY) screenshot.SaveBitmapFile(mem_dc, 'screenshot.bmp') mem_dc.DeleteDC() win32gui.DeleteObject(screenshot.GetHandle())
def do_test(): if not set_dpi_aware(): return hwnd = find_mine() l, t, w, h = get_client_rect(hwnd) handle_client_dc = win32gui.GetDC(hwnd) client_dc = win32ui.CreateDCFromHandle(handle_client_dc) mem_dc = client_dc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(client_dc, w, h) mem_dc.SelectObject(bmp) mine_area = get_mine_area(get_shot(bmp, mem_dc, client_dc, l, t, w, h)) while True: # get window shot img_shot = get_shot(bmp, mem_dc, client_dc, l, t, w, h) # process digits = process_mine_img(img_shot, mine_area) print digits break mem_dc.DeleteDC() client_dc.DeleteDC() win32gui.ReleaseDC(hwnd, handle_client_dc)
def extract_icon(exefilename): """Get the first resource icon from win32 exefilename and returns it a s PNG bytes array""" ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) large, small = win32gui.ExtractIconEx(exefilename,0) temp_dir = tempfile.mkdtemp() try: hdc = win32ui.CreateDCFromHandle( win32gui.GetDC(0) ) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap( hdc, ico_x, ico_x ) hdc = hdc.CreateCompatibleDC() hdc.SelectObject( hbmp ) hdc.DrawIcon( (0,0), large[0] ) bmp_temp = os.path.join(temp_dir,"icon.bmp") hbmp.SaveBitmapFile(hdc,bmp_temp) im = Image.open(bmp_temp) png_temp = os.path.join(temp_dir,"icon.png") with open(png_temp,'wb') as png: im.save(png, "PNG") result = open(png_temp,'rb').read() return result finally: win32gui.DestroyIcon(small[0]) win32gui.DestroyIcon(large[0]) if os.path.isdir(temp_dir): shutil.rmtree(temp_dir)
def get_pixel_rgb(pos): hwnd = get_hos_handler() x, y = pos dc = win32gui.GetDC(hwnd) rgbint = win32gui.GetPixel(dc, x, y) win32gui.ReleaseDC(hwnd, dc) return rgbint2rgbtuple(rgbint)
def is_empty_pixel(offset_ratio_x, offset_ratio_y): rect = win32gui.GetClientRect(rotmg_hwnd) hdc = win32gui.GetDC(rotmg_hwnd) r, g, b = get_pixel_rgb(hdc, int(rect[2] * offset_ratio_x), int(rect[3] * offset_ratio_y)) return abs(r - EMPTY_R) < EPSILON and abs(g - EMPTY_G) < EPSILON and abs( b - EMPTY_B) < EPSILON
def getPixel(x, y): hwnd = win32gui.WindowFromPoint((x, y)) hdc = win32gui.GetDC(hwnd) x1, y1 = win32gui.ScreenToClient(hwnd, (x, y)) color = win32gui.GetPixel(hdc, x1, y1) win32gui.ReleaseDC(hwnd, hdc) return color % 256, color / 256 % 256, color / 256 / 256
def get_icon(PATH, size): SHGFI_ICON = 0x000000100 SHGFI_ICONLOCATION = 0x000001000 if size == "small": SHIL_SIZE = 0x00001 elif size == "large": SHIL_SIZE = 0x00002 else: raise TypeError( "Invalid argument for 'size'. Must be equal to 'small' or 'large'") ret, info = shell.SHGetFileInfo( PATH, 0, SHGFI_ICONLOCATION | SHGFI_ICON | SHIL_SIZE) hIcon, iIcon, dwAttr, name, typeName = info ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), hIcon) win32gui.DestroyIcon(hIcon) bmpinfo = hbmp.GetInfo() bmpstr = hbmp.GetBitmapBits(True) img = Image.frombuffer("RGBA", (bmpinfo["bmWidth"], bmpinfo["bmHeight"]), bmpstr, "raw", "BGRA", 0, 1) if size == "small": img = img.resize((16, 16), Image.ANTIALIAS) return img
def get_real_size(): hDC = win32gui.GetDC(0) # 横向分辨率 w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES) # 纵向分辨率 h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES) return w, h
def get_icon(filepath: Optional[str], icon_save_directory: Optional[str] = None) -> Optional[str]: if not filepath: return None # no file path to save the icon from # TODO: Get icons of different sizes. small, large = win32gui.ExtractIconEx(filepath, 0, 10) if len(large) <= 0: return None # no icon to extract if len(small) > 0: win32gui.DestroyIcon(small[0]) # get rid of the small one hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYICON) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_y) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) executable_path = Path(filepath) icon_path = icon_name = f"icon_{executable_path.name}.bmp" if icon_save_directory: icon_path = str((Path(icon_save_directory) / icon_name).resolve()) hbmp.SaveBitmapFile(hdc, icon_path) with Image.open(icon_path) as img: buffered = BytesIO() img.save(buffered, format="PNG") image_string = base64.b64encode(buffered.getvalue()).decode() if not icon_save_directory: Path(icon_path).unlink() return image_string
def checkHealth(keyCode): x, y = calculateHPxy(80) color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) r, g, b = rgbint2rgbtuple(color) if r < 50: time.sleep(0.3) useSkill(keyCode)
def save_icon(icon_path, save_path): if icon_path == "Error: No path found": return False icon_path = icon_path.replace("\\", "/") try: iconX = win32api.GetSystemMetrics(win32con.SM_CXICON) iconY = win32api.GetSystemMetrics(win32con.SM_CXICON) large, small = win32gui.ExtractIconEx(icon_path, 0) win32gui.DestroyIcon(small[0]) hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, iconX, iconX) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), large[0]) bmpstr = hbmp.GetBitmapBits(True) from PIL import Image img = Image.frombuffer('RGBA', (32, 32), bmpstr, 'raw', 'BGRA', 0, 1) extrema = img.convert("L").getextrema() if "Chrome" in icon_path: pass # print("TEST") if extrema[1] < 250: img.save(save_path) return True except Exception as e: # print("Error:") # print(e) return False
def get_resolution(self): hDC = win32gui.GetDC(0) self.resolution = win32print.GetDeviceCaps( hDC, win32con.DESKTOPHORZRES) / win32api.GetSystemMetrics( win32con.SM_CXSCREEN) self.logger.get_log().debug('屏幕分辨率为:' + str(self.resolution)) return None
def get_icon_from_window(hwnd): """Create an icon file in the temp directory for the window handle and return its path. Actually, it is not unclear how the Windows API works to retrieve the icon info and save it as icon... """ hicon = win32api.SendMessage(hwnd, win32con.WM_GETICON, win32con.ICON_BIG) if hicon == 0: hicon = win32api.SendMessage(hwnd, win32con.WM_GETICON, win32con.ICON_SMALL) if hicon == 0: hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICON) if hicon == 0: hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICONSM) if hicon == 0: hicon = get_hicon_from_exe(hwnd) if hicon == 0: return None ico_x = win32api.GetSystemMetrics(win32con.SM_CXICON) # creating a destination memory DC hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, ico_x, ico_x) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), hicon) # file_path = TEMP_DIR + "\Icontemp" + str(hwnd) + ".bmp" file_path = ICONFILE_TEMP_STR.format(str(hwnd)) hbmp.SaveBitmapFile(hdc, file_path) return file_path
def getScale(self): hDC = win32gui.GetDC(0) widthOriginal = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES) #heightOriginal = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES) #dpiOriginal = win32print.GetDeviceCaps(hDC, win32con.LOGPIXELSX) widthReal = GetSystemMetrics(0) #heightReal = GetSystemMetrics(1) return widthOriginal / widthReal
def brain_eval(x, y): # TODO check if it works as expected wnd = win32gui.GetForegroundWindow() dc = win32gui.GetDC(wnd) rc = win32gui.GetClientRect(wnd) c = str(agent.board[x, y]) win32gui.ExtTextOut(dc, rc[2] - 15, 3, 0, None, c, ()) win32gui.ReleaseDC(wnd, dc)
def getWH(self): """获取真实的分辨率""" hDC = win32gui.GetDC(0) # 横向分辨率 w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES) # 纵向分辨率 h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES) return w,h
def readPixel(x, y): if x >= 1920: x = 1919 if y >= 1080: y = 1079 color = win32gui.GetPixel(win32gui.GetDC(win32gui.GetActiveWindow()), x, y) r, g, b = rgbint2rgbtuple(color) return r, g, b
def get_hdc(): hwnd = win32gui.FindWindow(None, "Kokoro@kokoro") if not hwnd: print('Window not found') exit(1) hdc = win32gui.GetDC(hwnd) assert hdc return hwnd, hdc
def drawtext(self, text): ''' 在鼠标所在为止写入一个字符串 ''' t = win32gui.GetDC(win32gui.GetDesktopWindow()) w,h = win32api.GetSystemMetrics(0),win32api.GetSystemMetrics(1) x,y = win32api.GetCursorPos() win32gui.DrawText(t,text,-1,(x,y,w,h),8)
def IconToFile(hlib, tmpDirName, group_name): libc = ctypes.CDLL(ctypes.util.find_library('c')) libc.memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t] libc.memcpy.restype = ctypes.c_char_p # patch FindResourceW, ctypes.windll.kernel32.SizeofResource FindResourceW = ctypes.windll.kernel32.FindResourceW FindResourceW.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p ] FindResourceW.restype = ctypes.c_void_p SizeofResource = ctypes.windll.kernel32.SizeofResource SizeofResource.argtypes = [ctypes.c_void_p, ctypes.c_void_p] SizeofResource.restype = ctypes.c_size_t hRes = win32api.LoadResource(hlib, win32con.RT_GROUP_ICON, group_name) mem_icon_dir = ctypes.windll.kernel32.LockResource(hRes) # 32 bits color; 16 and 256 colors are too old icon_size = 256 icon_name = ctypes.windll.user32.LookupIconIdFromDirectoryEx( mem_icon_dir, True, icon_size, icon_size, 0x00000000) sys.stderr.write("icon_name=%s\n" % str(icon_name)) hResInfo = FindResourceW(hlib, icon_name, win32con.RT_ICON) size = ctypes.windll.kernel32.SizeofResource(hlib, hResInfo) rec = win32api.LoadResource(hlib, win32con.RT_ICON, icon_name) mem_icon = ctypes.windll.kernel32.LockResource(rec) # And this is some differ (copy data to Python buffer) binary_data = (ctypes.c_ubyte * size)() libc.memcpy(binary_data, mem_icon, size) hIconRet = ctypes.windll.user32.CreateIconFromResourceEx( binary_data, size, True, 0x00030000, 0, 0, 0x00000000) info = win32gui.GetIconInfo(hIconRet) bminfo = win32gui.GetObject(info[4]) # generate bitmap by drawing the icon hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, bminfo.bmWidth, bminfo.bmHeight) hcdc = hdc.CreateCompatibleDC() hcdc.SelectObject(hbmp) win32gui.DrawIconEx(hcdc.GetHandleOutput(), 0, 0, hIconRet, bminfo.bmWidth, bminfo.bmHeight, 0, 0, 0x0003) # Need temp directory or generate image on the fly, for inclusion into an HTML page. # Temp file visible from HTTP server. # An alternative is to send the file content to a socket stream. # MIME type is "image/bmp" imgFilNam = "icon-%03dx%03d-%05d-%03d.bmp" % ( bminfo.bmWidth, bminfo.bmHeight, group_name, icon_name) if tmpDirName: imgFilNam = tmpDirName + imgFilNam sys.stderr.write("Generating %s\n" % imgFilNam) hbmp.SaveBitmapFile(hcdc, imgFilNam) win32gui.DestroyIcon(hIconRet) return imgFilNam
def bitmapFromHIcon(hIcon): hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0)) hbmp = win32ui.CreateBitmap() hbmp.CreateCompatibleBitmap(hdc, 40, 40) hdc = hdc.CreateCompatibleDC() hdc.SelectObject(hbmp) hdc.DrawIcon((0, 0), hIcon) hdc.DeleteDC() return hbmp.GetHandle()
def _get_device_caps(constant): dc = None try: gdi32 = ctypes.windll.gdi32 dc = win32gui.GetDC(None) return gdi32.GetDeviceCaps(dc, constant) finally: if dc: win32gui.ReleaseDC(None, dc)