def drawCrossHair(hDc, centerX, centerY, size=10, lineWidth=1, color=COLOR_RED): hPen= win32gui.CreatePen(win32con.PS_SOLID, lineWidth, color) win32gui.SelectObject(hDc, hPen) win32gui.MoveToEx(hDc, centerX-size, centerY) win32gui.LineTo(hDc, centerX+size, centerY) win32gui.MoveToEx(hDc, centerX, centerY+size) win32gui.LineTo(hDc, centerX, centerY-size)
def _win_message(self, hWnd, message, wParam, lParam): if message == win32_contants.WM_PAINT: device_context_handle, paintStruct = win32gui.BeginPaint(hWnd) dpiScale = ctypes.windll.gdi32.GetDeviceCaps( device_context_handle, win32_contants.LOGPIXELSX) / 60.0 fontSize = 14 # 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.lfHeight = 20 lf.lfWeight = 0 # Use nonantialiased to remove the white edges around the text. lf.lfQuality = win32con.NONANTIALIASED_QUALITY hf = win32gui.CreateFontIndirect(lf) win32gui.SetTextColor(device_context_handle, win32_color(self.font_color)) win32gui.SelectObject(device_context_handle, hf) self._draw(device_context_handle) win32gui.EndPaint(hWnd, paintStruct) return 0 elif message == win32_contants.WM_DESTROY: win32gui.PostQuitMessage(0) return 0 else: return ctypes.windll.user32.DefWindowProcW(hWnd, message, wParam, lParam)
def OnPaint_1(hwnd, msg, wp, lp): dc, ps = win32gui.BeginPaint(hwnd) win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED) br = win32gui.CreateSolidBrush(win32api.RGB(255, 0, 0)) win32gui.SelectObject(dc, br) angle = win32gui.GetWindowLong(hwnd, win32con.GWL_USERDATA) win32gui.SetWindowLong(hwnd, win32con.GWL_USERDATA, angle + 2) r_angle = angle * (math.pi / 180) win32gui.SetWorldTransform( dc, { "M11": math.cos(r_angle), "M12": math.sin(r_angle), "M21": math.sin(r_angle) * -1, "M22": math.cos(r_angle), "Dx": 250, "Dy": 250, }, ) win32gui.MoveToEx(dc, 250, 250) win32gui.BeginPath(dc) win32gui.Pie(dc, 10, 70, 200, 200, 350, 350, 75, 10) win32gui.Chord(dc, 200, 200, 850, 0, 350, 350, 75, 10) win32gui.LineTo(dc, 300, 300) win32gui.LineTo(dc, 100, 20) win32gui.LineTo(dc, 20, 100) win32gui.LineTo(dc, 400, 0) win32gui.LineTo(dc, 0, 400) win32gui.EndPath(dc) win32gui.StrokeAndFillPath(dc) win32gui.EndPaint(hwnd, ps) return 0
def wndProc_edge(self, hWnd, message, wParam, lParam): if message == win32con.WM_PAINT: hdc, paintStruct = win32gui.BeginPaint(hWnd) dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0 fontSize = self.fontSize + 12 win32gui.SetTextColor(hdc, self.color_edge) # https://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx lf = win32gui.LOGFONT() lf.lfFaceName = "微軟正黑體" lf.lfHeight = int(round(dpiScale * fontSize)) lf.lfWeight = 700 # 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) # https://msdn.microsoft.com/en-us/library/windows/desktop/dd162498(v=vs.85).aspx win32gui.DrawTextW( hdc, self.text, -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 prep_menu_icon(self, 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) brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) 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 prep(self): ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON) ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON) lr, sm = win32gui.ExtractIconEx(self.dll, self.id) win32gui.DestroyIcon(lr[0]) hicon = sm[0] hdcBitmap = win32gui.CreateCompatibleDC(0) hdcScreen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y) hbmOld = win32gui.SelectObject(hdcBitmap, hbm) brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) 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 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 draw_pixel(): hwin = win32gui.GetDesktopWindow() hdc = win32gui.GetDC(hwin) # 점찍기 red = win32api.RGB(255, 0, 0) win32gui.SetPixel(hdc, 0, 0, red) win32gui.SetPixel(hdc, 0, 1, red) win32gui.SetPixel(hdc, 0, 2, red) win32gui.SetPixel(hdc, 0, 3, red) # 사각형그리기 pen = win32gui.CreatePen(win32con.PS_SOLID, 5, win32api.RGB(0, 0, 255)) oldPen = win32gui.SelectObject(hdc, pen) win32gui.Rectangle(hdc, 50, 50, 100, 100) win32gui.SelectObject(hdc, oldPen) win32gui.DeleteObject(pen)
def _draw_text(self, handle: int, box: tuple, text: str, color: tuple, font: (dict, tuple)) -> tuple: """Draw text in the given location""" font = self._build_font(font, self._get_dpi_scale(handle)) gui.SelectObject(handle, font) gui.SetTextColor(handle, self._color(color)) return gui.DrawText( handle, text, -1, box, con.DT_NOCLIP | con.DT_LEFT | con.DT_SINGLELINE | con.DT_TOP)
def __enter__(self): if self.font_config: self.new_font_object = CreateFontW( self.height, self.width, self.escapement, self.orientation, self.weight, self.italic, self.underline, self.strikeOut, self.charSet, self.outPrecision, self.clipPrecision, self.quality, self.pitchAndFamily, self.faceName) self.old_font_object = win32gui.SelectObject( self.printer.printer_dc, self.new_font_object)
def highLight(self): """高亮此区域 """ hwnd = win32gui.GetDesktopWindow() hDesktopDC = win32gui.GetWindowDC(hwnd) oldRop2 = ctypes.windll.gdi32.SetROP2(hDesktopDC, win32con.R2_NOTXORPEN) newPen = win32gui.CreatePen(win32con.PS_SOLID, 3, 0) oldPen = win32gui.SelectObject(hDesktopDC, newPen) #在指示窗口周围显示闪烁矩形 for i in range(2): win32gui.Rectangle(hDesktopDC, self._rect[0], self._rect[1], self._rect[2], self._rect[3]) time.sleep(0.2) win32gui.Rectangle(hDesktopDC, self._rect[0], self._rect[1], self._rect[2], self._rect[3]) time.sleep(0.3) ctypes.windll.gdi32.SetROP2(hDesktopDC, oldRop2) win32gui.SelectObject(hDesktopDC, oldPen) win32gui.DeleteObject(newPen) win32gui.ReleaseDC(hwnd,hDesktopDC)
def OnPaint(self, hWnd, msg, wparam, lparam): dc, ps = win32gui.BeginPaint(hWnd) wndrect = win32gui.GetClientRect(hWnd) wndwidth = wndrect[2] - wndrect[0] wndheight = wndrect[3] - wndrect[1] if os.path.isfile(FILENAME): hBitmap = win32gui.LoadImage(0, FILENAME, win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE) hdcBitmap = win32gui.CreateCompatibleDC(dc) hOldBitmap = win32gui.SelectObject(hdcBitmap, hBitmap) bminfo = win32gui.GetObject(hBitmap) win32gui.SetStretchBltMode(dc, win32con.COLORONCOLOR) win32gui.StretchBlt(dc, 0, 0, wndwidth, wndheight, hdcBitmap, 0, 0, bminfo.bmWidth, bminfo.bmHeight, win32con.SRCCOPY) win32gui.SelectObject(hdcBitmap, hOldBitmap) win32gui.EndPaint(hWnd, ps) return 0
def prepareFont(self): if self.font is None: self.font = win32gui.CreateFontIndirect(self.logfont) win32gui.SelectObject(self.dch, self.font) if self.lpi is None: self.leading = abs(self.logfont.lfHeight ) * self.ratio_size2leading # 20070205 else: self.leading = inch / self.lpi """
def draw_focus_rectangle(cls, region: Region) -> None: """Draw a highlight region around given region Args: region (Region): [description] """ dc = win32gui.GetDC(0) pen = win32gui.CreatePen(win32con.PS_SOLID, 2, 0) win32gui.DrawFocusRect(dc, region.to_tuple()) win32gui.SelectObject(dc, pen) win32gui.DeleteDC(dc)
def drawLeftArc(self, hdc, pos, radius, width, span, percent, color=ColorCode.BLACK): if percent > 0.0: # Get arc center coordinates xc = pos[0] yc = pos[1] # Calculate a2 a1 = math.radians(span / 2) a2 = math.asin(radius * math.sin(a1) / (radius + width)) # calculate displacement on x and y axis dx = radius * math.cos(a2) dy = radius * math.sin(a2) # calculate starting point coordinates xs = int(xc - dx) ys = int(yc + dy) a2d = math.degrees(a2) # determines arc span span = 2 * a2d # sets the percentage to be drawn n = percent # sets arc fill color sb = win32gui.CreateSolidBrush(color) win32gui.SelectObject(hdc, sb) # draws the outline of the arc win32gui.BeginPath(hdc) win32gui.MoveToEx(hdc, xs, ys) win32gui.AngleArc(hdc, xc, yc, radius + width, 180 + a2d, -int(n * span)) win32gui.AngleArc(hdc, xc, yc, radius, int(180 - a2d + (1 - n) * span), int(n * span)) win32gui.EndPath(hdc) # fills the arc with outer stroke win32gui.StrokeAndFillPath(hdc) # returns the next arc span and radius return span, (radius + width) else: # if its not drawn, returns original arc span and radius return span, radius
def OnPaint(hwnd, msg, wp, lp): global dx dc, ps=win32gui.BeginPaint(hwnd) win32gui.SetGraphicsMode(dc, win32con.GM_ADVANCED) l,t,r,b=win32gui.GetClientRect(hwnd) br=win32gui.CreateSolidBrush(win32api.RGB(0,0,255)) win32gui.SelectObject(dc, br) win32gui.FillRect(dc,(200+dx,200+dx,100+dx,100+dx),br) dx=(dx+10)%100 win32gui.EndPaint(hwnd, ps) return 0
def prep_menu_icon(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) hdc_bitmap = win32gui.CreateCompatibleDC(0) hdc_screen = win32gui.GetDC(0) hbm = win32gui.CreateCompatibleBitmap(hdc_screen, ico_x, ico_y) hbm_old = win32gui.SelectObject(hdc_bitmap, hbm) # 填满背景 brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdc_bitmap, (0, 0, 16, 16), brush) # "GetSysColorBrush返回缓存的画笔而不是分配新的画笔" # - 暗示没有DeleteObject # 画出图标 win32gui.DrawIconEx(hdc_bitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL) win32gui.SelectObject(hdc_bitmap, hbm_old) win32gui.DeleteDC(hdc_bitmap) return hbm
def write_text(text=""): hwin = win32gui.GetDesktopWindow() hdc = win32gui.GetDC(hwin) # 텍스트 옵션 font = win32ui.CreateFont({"name": "Arial", "height": 64, "weight": 400}) oldFont = win32gui.SelectObject(hdc, font.GetSafeHandle()) #win32gui.SetTextColor(hdc, win32api.RGB(0,0,0)) #win32gui.SetBkColor(hdc, win32api.RGB(255, 255, 255)) rect = win32gui.GetClientRect(hwin) win32gui.DrawText( hdc, text, len(text), rect, win32con.DT_BOTTOM | win32con.DT_RIGHT | win32con.DT_SINGLELINE | win32con.DT_WORDBREAK #win32con.DT_CENTER|win32con.DT_VCENTER|win32con.DT_SINGLELINE|win32con.DT_WORDBREAK ) win32gui.SelectObject(hdc, oldFont) win32gui.DeleteObject(font.GetSafeHandle()) win32gui.ReleaseDC(hwin, hdc)
def OnPaint(hwnd, msg, wp, lp): """Windows needs repainting""" dc, ps = win32gui.BeginPaint(hwnd) #Draw red circle br = win32gui.CreateSolidBrush(win32api.RGB(255, 0, 0)) win32gui.SelectObject(dc, br) win32gui.Ellipse(dc, 20, 20, 120, 120) #Draw green rectangle br = win32gui.CreateSolidBrush(win32api.RGB(0, 255, 0)) win32gui.SelectObject(dc, br) win32gui.Rectangle(dc, 150, 20, 300, 120) #Draw blue triangle br = win32gui.CreateSolidBrush(win32api.RGB(0, 0, 255)) win32gui.SelectObject(dc, br) win32gui.Polygon(dc, [(400, 20), (350, 120), (450, 120)]) win32gui.EndPaint(hwnd, ps) return 0
def prep_menu_icon(self, icon): # 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 on_paint(self, hwnd, message, wparam, lparam): """Draw current selection rectangle.""" hdc, paint = win32gui.BeginPaint(hwnd) # Selection not started yet if self._selection is None: win32gui.EndPaint(hwnd, paint) return 0 brush = win32gui.GetStockObject(win32con.NULL_BRUSH) pen = win32gui.CreatePen(win32con.PS_SOLID, self.REGION_WIDTH, self.REGION_COLOR) brush_default = win32gui.SelectObject(hdc, brush) pen_default = win32gui.SelectObject(hdc, pen) win32gui.Rectangle(hdc, *self._selection) win32gui.SelectObject(hdc, pen_default) win32gui.SelectObject(hdc, brush_default) win32gui.EndPaint(hwnd, paint) return 0
def _thread_function(x, y, w, h, delay): [x, y, w, h] = map(int, [x, y, w, h]) delay = float(delay) # Получим контекст всех дисплев или всего рабочего стола: #scr_hdc = win32gui.GetDC(0) scr_hdc = win32gui.CreateDC('DISPLAY', None, None) mem_hdc = win32gui.CreateCompatibleDC( scr_hdc ) # New context of memory device. This one is compatible with 'scr_hdc' new_bitmap_h = win32gui.CreateCompatibleBitmap(scr_hdc, w + 2, h + 2) win32gui.SelectObject( mem_hdc, new_bitmap_h ) # Returns 'old_bitmap_h'. It will be deleted automatically. # Сохраняем рамочку в 1 пиксель (она вокруг области (x,y,w,h)): _cp_boundary(mem_hdc, 0, 0, scr_hdc, x - 1, y - 1, w + 2, h + 2) # Рисуем подсветку области: # brush = win32gui.CreateSolidBrush(win32api.RGB(255,0,0)) win32gui.SelectObject(scr_hdc, win32gui.GetStockObject(win32con.NULL_BRUSH)) pen = win32gui.CreatePen(win32con.PS_DOT, 1, win32api.RGB(148, 0, 0)) win32gui.SelectObject(scr_hdc, pen) for i in range(2): win32gui.Rectangle(scr_hdc, x - 1, y - 1, x + w + 1, y + h + 1) # Восстаналиваема рамочку: time.sleep(delay) _cp_boundary(scr_hdc, x - 1, y - 1, mem_hdc, 0, 0, w + 2, h + 2) #win32gui.ReleaseDC(scr_hdc, 0) win32gui.DeleteDC(scr_hdc) win32gui.DeleteDC(mem_hdc) win32gui.DeleteObject(new_bitmap_h)
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 drawRect(pos, pred, colors): hwnd = win32gui.GetDesktopWindow() # 定义框颜色 hPen = win32gui.CreatePen(win32con.PS_SOLID, 3, win32api.RGB(colors[pred][0], colors[pred][1], colors[pred][2])) win32gui.InvalidateRect(hwnd, None, True) win32gui.UpdateWindow(hwnd) win32gui.RedrawWindow(hwnd, None, None, win32con.RDW_FRAME | win32con.RDW_INVALIDATE | win32con.RDW_UPDATENOW | win32con.RDW_ALLCHILDREN) # 根据窗口句柄获取窗口的设备上下文DC(Divice Context) hwndDC = win32gui.GetDC(hwnd) win32gui.SelectObject(hwndDC, hPen) # 定义透明画刷,这个很重要! hbrush = win32gui.GetStockObject(win32con.NULL_BRUSH) prebrush = win32gui.SelectObject(hwndDC, hbrush) # 左上到右下的坐标 win32gui.Rectangle(hwndDC, pos[0] - 240, pos[1] - 135, pos[0] + 240, pos[1] + 135) win32gui.SaveDC(hwndDC) win32gui.SelectObject(hwndDC, prebrush) # 回收资源 win32gui.DeleteObject(hPen) win32gui.DeleteObject(hbrush) win32gui.DeleteObject(prebrush) win32gui.ReleaseDC(hwnd, hwndDC)
def prep_menu_icon(self, icon): if DEBUG: print(sys._getframe(0).f_code.co_name) # 首先加载图标。 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) # 填满背景。 brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU) win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush) # "GetSysColorBrush返回缓存的画笔而不是分配新的画笔。" # - 暗示没有DeleteObject # 画出图标 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 draw_ellipse(cls, region: Region, color: RGB = None) -> None: """Draws a colored ellipse around given region Args: region (Region): [description] color (RGB, optional): [description]. Defaults to None. """ if not color: color = RGB(0, 255, 0) dc = win32gui.GetDC(0) pen = win32gui.CreatePen(win32con.PS_SOLID, 2, color.to_color_ref()) brush = win32gui.CreateBrushIndirect({ 'Style': win32con.BS_NULL, 'Color': -1, 'Hatch': win32con.HS_DIAGCROSS }) win32gui.SelectObject(dc, pen) win32gui.SelectObject(dc, brush) win32gui.Ellipse(dc, *region.to_tuple()) win32gui.DeleteObject(pen) win32gui.DeleteObject(brush) win32gui.DeleteDC(dc)
def _take_screenshot_with_native_api(self, x, y, w, h, hwnd): if hwnd is None: scr_hdc = win32gui.CreateDC('DISPLAY', None, None) else: scr_hdc = win32gui.GetDC(hwnd) mem_hdc = win32gui.CreateCompatibleDC(scr_hdc) new_bitmap_h = win32gui.CreateCompatibleBitmap(scr_hdc, w, h) win32gui.SelectObject( mem_hdc, new_bitmap_h ) # Returns 'old_bitmap_h'. It will be deleted automatically. win32gui.BitBlt(mem_hdc, 0, 0, w, h, scr_hdc, x, y, win32con.SRCCOPY) bmp = win32ui.CreateBitmapFromHandle(new_bitmap_h) bmp_info = bmp.GetInfo() if bmp_info['bmHeight'] != h or bmp_info['bmWidth'] != w: raise FailExit('bmp_info = {bmp}, but (w, h) = ({w}, {h})'.format( bmp=bmp_info, width=w, height=h)) if bmp_info['bmType'] != 0 or bmp_info['bmPlanes'] != 1: raise FailExit( 'bmp_info = {bmp}: bmType !=0 or bmPlanes != 1'.format( bmp=str(bmp_info))) if bmp_info['bmBitsPixel'] % 8 != 0: raise FailExit( 'bmp_info = {bmp}: bmBitsPixel mod. 8 is not zero'.format( bmp=str(bmp_info))) bmp_arr = list(bmp.GetBitmapBits()) if len(bmp_arr) == w * h * 4: del bmp_arr[3:: 4] # Delete alpha channel. TODO: Is it fast enough??? elif len(bmp_arr) != w * h * 3: raise FailExit('An error occurred while read bitmap bits') result = np.array(bmp_arr, dtype=np.uint8).reshape((h, w, 3)) win32gui.DeleteDC(mem_hdc) win32gui.DeleteObject(new_bitmap_h) if not hwnd: win32gui.DeleteDC(scr_hdc) else: win32gui.ReleaseDC(hwnd, scr_hdc) return result
def draw_line(cls, points: List[Point2D], color: RGB = None) -> None: """[summary] Args: points (List[Point2D]): [description] color (RGB, optional): [description]. Defaults to None. """ if not color: color = RGB(0, 255, 0) # GetDC(hwnd), jos haluaa nimenomaan tietylle ikkunalle... dc = win32gui.GetDC(0) pen = win32gui.CreatePen(win32con.PS_SOLID, 2, color.to_color_ref()) win32gui.SelectObject(dc, pen) lista = [p.to_tuple() for p in points] win32gui.Polyline(dc, lista) win32gui.DeleteObject(pen) win32gui.DeleteDC(dc)
def debugRender(hWnd, hdc, paintStruct): dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0 fontSize = 12 # http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx lf = win32gui.LOGFONT() lf.lfFaceName = "Arial" 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) logging.debug(rect) # http://msdn.microsoft.com/en-us/library/windows/desktop/dd162498(v=vs.85).aspx win32gui.DrawText( hdc, 'Text on the screen', -1, rect, win32con.DT_CENTER | win32con.DT_NOCLIP | win32con.DT_SINGLELINE | win32con.DT_VCENTER)
def get_color(pos): hdc_screen = win32gui.CreateDC("DISPLAY", "", None) hmem_dc = win32gui.CreateCompatibleDC(hdc_screen) h_bitmap = win32gui.CreateCompatibleBitmap(hdc_screen, 1, 1) h_old_bitmap = win32gui.SelectObject(hmem_dc, h_bitmap) win32gui.BitBlt(hmem_dc, 0, 0, 1, 1, hdc_screen, pos[0], pos[1], win32con.SRCCOPY) win32gui.DeleteDC(hdc_screen) win32gui.DeleteDC(hmem_dc) x = win32ui.CreateBitmapFromHandle(h_bitmap) bits = x.GetBitmapBits(True) return struct.unpack('I', bits)[0]