Пример #1
0
    def wndProc(self, hWnd, message, wParam, lParam):

        if message == win32con.WM_PAINT:
            hdc, paintStruct = win32gui.BeginPaint(hWnd)

            # Font configuration
            dpiScale = win32ui.GetDeviceCaps(hdc, win32con.LOGPIXELSX) / 60.0
            fontSize = 10

            # http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx
            lf = win32gui.LOGFONT()
            lf.lfFaceName = "Tahoma"
            lf.lfHeight = int(round(dpiScale * fontSize))
            lf.lfWeight = 700  # bold
            lf.lfQuality = win32con.NONANTIALIASED_QUALITY  # Use nonantialiased to remove the white edges around the text.

            hf = win32gui.CreateFontIndirect(lf)

            win32gui.SelectObject(hdc, hf)

            br = win32gui.CreateSolidBrush(win32api.RGB(255, 0, 0))
            win32gui.SelectObject(hdc, br)

            # Update positions
            self.updatePositions()

            # Bars
            # Positions the bars
            if self.mounted:
                xc = self.axcm
                yc = self.aycm
            else:
                xc = self.axc
                yc = self.ayc

            r = self.aradius
            dr = self.awidth
            alpha = self.aangle

            #print(xc,yc)

            ## Text
            # Positions the text
            pleft = self.tleft
            ptop = self.ttop
            pright = self.tright
            pbottom = self.tbottom
            spc = self.tspc

            #print(pleft,ptop,pright,pbottom)
            if self.setup:
                sr = alpha
                rr = r
                for _ in range(2):
                    sr, rr = self.drawRightArc(hdc, (xc, yc), rr, dr, sr, 1.0,
                                               ColorCode.ORANGE)

                sl = alpha
                rl = r
                for _ in range(2):
                    sl, rl = self.drawLeftArc(hdc, (xc, yc), rl, dr, sl, 1.0,
                                              ColorCode.ORANGE)

                for i in range(50):
                    pos = (pleft, ptop + i * spc, pright, pbottom)
                    self.drawTextLabel(hdc, pos, ColorCode.ORANGE,
                                       'ExampleText')
                    self.drawTimerLabel(hdc, pos, ColorCode.ORANGE, float(i))

            else:
                sr = alpha
                rr = r
                for idx, action in enumerate(self.rightArcToDraw):
                    sr, rr = self.drawRightArc(hdc, (xc, yc), rr, dr, sr,
                                               action.getPercentage(),
                                               action.color)

                sl = alpha
                rl = r
                for idx, action in enumerate(self.leftArcToDraw):
                    sl, rl = self.drawLeftArc(hdc, (xc, yc), rl, dr, sl,
                                              action.getPercentage(),
                                              action.color)

                for idx, group in enumerate(self.groupsToDraw):
                    pos = (pleft, ptop + idx * spc, pright, pbottom)
                    self.drawTextLabel(hdc, pos, group.color, group.labelText)
                    self.drawTimerLabel(hdc, pos, group.color, group.countdown)

                k = idx + 2
                for idx, action in enumerate(self.actionsToDraw):
                    if (idx + 1) in self.emptyLines: k = k + 1

                    pos = (pleft, ptop + (idx + k) * spc, pright, pbottom)
                    self.drawTextLabel(hdc, pos, action.color,
                                       action.labelText)
                    self.drawTimerLabel(hdc, pos, action.color,
                                        action.countdown)

                k = k + idx + 2
                for idx, equip in enumerate(self.equipmentToDraw):
                    #if (idx+1) in emptyLines : k=k+1

                    pos = (pleft, ptop + (idx + k) * spc, pright, pbottom)
                    self.drawTextLabel(hdc, pos, equip.color, equip.labelText)
                    self.drawTimerLabel(hdc, pos, equip.color, equip.countdown)

                win32gui.EndPaint(hWnd, paintStruct)
                return 0

        elif message == win32con.WM_DESTROY:
            win32gui.PostQuitMessage(0)
            return 0

        else:
            return win32gui.DefWindowProc(hWnd, message, wParam, lParam)
Пример #2
0
 def DoPaint(self, dc):
     dc.FillSolidRect(self.GetClientRect(), win32api.RGB(255, 0, 0))
Пример #3
0
itr = iter(hotkeys)

pygame.init()
screen = pygame.display.set_mode(
    (250, 100))  # For borderless, use pygame.NOFRAME
pygame.display.set_caption('')
fuchsia = (255, 0, 128)  # Transparency color
dark_red = (139, 100, 0)

# Set window transparency color
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(
    hwnd, win32con.GWL_EXSTYLE,
    win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0,
                                    win32con.LWA_COLORKEY)

f1 = pygame.font.Font(None, 36)
text1 = f1.render('', 1, (180, 0, 0))
screen.blit(text1, (10, 50))

while 1:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            exit()
        if i.type == pygame.MOUSEBUTTONDOWN:
            text1 = f1.render(next(itr), 1, (180, 200, 30))

    screen.fill(fuchsia)  # Transparent background
    pygame.draw.rect(screen, dark_red, pygame.Rect(30, 30, 60, 60))
Пример #4
0
win32print.StartDoc(pDC, ('desktop.bmp', None, None, 0))
win32print.StartPage(pDC)
win32gui.StretchBlt(pDC, 0, 0, int(printerwidth * .9), int(printerheight * .9),
                    pcDC, 0, 0, printerwidth, printerheight, win32con.SRCCOPY)

font = win32gui.LOGFONT()
font.lfHeight = int(printerheight / 20)
font.lfWidth = font.lfHeight
font.lfWeight = 150
font.lfItalic = 1
font.lfUnderline = 1
hf = win32gui.CreateFontIndirect(font)
win32gui.SelectObject(pDC, hf)
win32gui.SetBkMode(pDC, win32con.TRANSPARENT)
win32gui.SetTextColor(pDC, win32api.RGB(0, 255, 0))
win32gui.DrawText(
    pDC, 'Printed by Python!', -1,
    (0, 0, int(printerwidth * .9), int(printerheight * .9)),
    win32con.DT_RIGHT | win32con.DT_BOTTOM | win32con.DT_SINGLELINE)
win32print.EndPage(pDC)
win32print.EndDoc(pDC)

win32print.ClosePrinter(p)
win32gui.DeleteObject(dcBM)
win32gui.DeleteObject(pcBM)
win32gui.DeleteObject(hf)
win32gui.DeleteDC(dDC)
win32gui.DeleteDC(dcDC)
win32gui.DeleteDC(pDC)
win32gui.DeleteDC(pcDC)
Пример #5
0

def user_wait(duration):
    stop = time.time() + duration
    while time.time() < stop:
        time.sleep(0.5)
        pygame.display.set_mode((width, height), pygame.NOFRAME, 32)
    return


pygame.init()
twitch_bot_utils.printer("Dim scare! %s seconds" % times)
pygame.display.set_mode((width, height), pygame.NOFRAME, 32)
twitch_bot_utils.printer("Looking for window!")

while True:
    time.sleep(0.001)
    try:
        hwnd = win32gui.FindWindow(None, "pygame window")
        if hwnd:
            twitch_bot_utils.printer("Found window! hwnd: %s" % hwnd)
            set_top(hwnd)
            break
    except win32gui.error:
        twitch_bot_utils.printer("Error: window not found")

win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(0, 0, 0), 220,
                                    win32con.LWA_ALPHA)
user_wait(times)
twitch_bot_utils.printer("Done!")
Пример #6
0
 def DoPaint(self, dc):
     rc = self.GetClientRect()
     dc.SetBkMode(win32con.TRANSPARENT)
     dc.SetTextAlign(win32con.TA_BOTTOM)
     dc.SetTextColor(win32api.RGB(255, 0, 0))
     dc.TextOut(rc[0] + 20, rc[1] + (rc[3] - rc[1]) / 2, "Python rules")
Пример #7
0
def appendFrameRectToWindow(hW, x, y, w, h):
    hDc = win32gui.GetWindowDC(hW)
    hPen = win32gui.CreatePen(win32con.PS_SOLID, 10, win32api.RGB(255, 0, 255))
    win32gui.FrameRect(hDc, (x, y, x + w, y + h), hPen)
Пример #8
0
import win32api
import win32gui
import win32con
import win32ui

hWnd = win32gui.GetDesktopWindow()
# Retrieves a handle to the desktop window. The desktop window covers the entire screen.
# The desktop window is the area on top of which other windows are painted.
hdc = win32gui.GetDC(hWnd)
#win32gui.GetDC(None)
# A handle to the window whose DC is to be retrieved. If this value is NULL, GetDC
# retrieves the DC for the entire screen.

red = win32api.RGB(255, 0, 0)
win32gui.SetPixel(hdc, 0, 0, red)  # (0, 0)에 빨간 점 그리기

MyPen = win32gui.CreatePen(win32con.PS_SOLID, 5, win32api.RGB(0,0,255));
OldPen = win32gui.SelectObject(hdc, MyPen);

win32gui.Rectangle(hdc, 50, 50, 100, 100) # (50, 50, 100, 100)에 파란 선으로 사각형 그리기

win32gui.SelectObject(hdc, OldPen);
win32gui.DeleteObject(MyPen);

# 폰트 만들기
font_spec = {'name':'Arial', 'height':42, 'weight':30}
font = win32ui.CreateFont(font_spec)
#lf = win32gui.LOGFONT()
#lf.lfFaceName = "Times New Roman"
#lf.lfHeight = 100
#lf.lfWeight = win32con.FW_NORMAL
Пример #9
0
        def wnd_proc(h_wnd, message, w_param, l_param):
            """Displays a transparent window with some graphic elements
			Displays a transparent window with some graphic elements
			:param h_wnd: an input argument
			:returns: nothing
			"""
            if message == win32con.WM_QUIT:
                # print("Closing the window overlay")
                win32gui.PostQuitMessage(0)
                return 0

            if message == win32con.WM_PAINT:
                hdc, paint_struct = win32gui.BeginPaint(h_wnd)
                win32gui.SetGraphicsMode(hdc, win32con.GM_ADVANCED)
                win32gui.BringWindowToTop(h_wnd)

                for r in self.graphical_elements:

                    if 'geometry' in r:
                        geometry = r['geometry']
                    else:
                        geometry = None
                    if 'x' in r:
                        x = r['x'] - self.x_min
                    else:
                        x = 0
                    if 'y' in r:
                        y = r['y'] - self.y_min
                    else:
                        y = 0
                    if 'width' in r:
                        width = r['width']
                    else:
                        width = 100
                    if 'height' in r:
                        height = r['height']
                    else:
                        height = 100
                    if 'xyrgb_array' in r:
                        xyrgb_array = r['xyrgb_array']
                    else:
                        xyrgb_array = ((15, 15, 255, 0, 0), (15, 45, 0, 255,
                                                             0), (45, 30, 0, 0,
                                                                  255))
                    if 'color' in r:
                        color_r = r['color'][0]
                        color_g = r['color'][1]
                        color_b = r['color'][2]
                    else:
                        color_r = 255
                        color_g = 0
                        color_b = 0

                    if 'thickness' in r:
                        thickness = r['thickness']
                    else:
                        thickness = 0

                    if 'angle' in r:
                        angle = r['angle']
                    else:
                        angle = 0

                    if 'geometry' in r and r['geometry'] is Shape.triangle:
                        vertices = ()
                        for xyrgb in xyrgb_array:
                            vertices = vertices + (
                                {
                                    'x': int(round(xyrgb[0])) - self.x_min,
                                    'y': int(round(xyrgb[1])) - self.y_min,
                                    'Red': xyrgb[2] * 256,
                                    'Green': xyrgb[3] * 256,
                                    'Blue': xyrgb[4] * 256,
                                    'Alpha': 0
                                }, )
                        mesh = ((0, 1, 2), )
                        win32gui.GradientFill(hdc, vertices, mesh,
                                              win32con.GRADIENT_FILL_TRIANGLE)

                    if 'brush_color' in r:
                        brush_color_r = r['brush_color'][0]
                        brush_color_g = r['brush_color'][1]
                        brush_color_b = r['brush_color'][2]
                    else:
                        brush_color_r = 255
                        brush_color_g = 255
                        brush_color_b = 255

                    if thickness == 0:
                        color_r = brush_color_r
                        color_g = brush_color_g
                        color_b = brush_color_b

                    if 'font_size' in r:
                        font_size = r['font_size']
                    else:
                        font_size = 18

                    if 'font_name' in r:
                        font_name = r['font_name']
                    else:
                        font_name = "Arial"

                    my_brush = None
                    if 'brush' in r and width > 1 and height > 1:
                        brush = r['brush']
                        brush_color = win32api.RGB(brush_color_r,
                                                   brush_color_g,
                                                   brush_color_b)
                        if brush is Brush.solid:
                            my_brush = win32gui.CreateSolidBrush(brush_color)
                        elif brush is Brush.b_diagonal:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_BDIAGONAL, brush_color)
                        elif brush is Brush.cross:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_CROSS, brush_color)
                        elif brush is Brush.diag_cross:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_DIAGCROSS, brush_color)
                        elif brush is Brush.f_diagonal:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_FDIAGONAL, brush_color)
                        elif brush is Brush.horizontal:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_HORIZONTAL, brush_color)
                        elif brush is Brush.vertical:
                            my_brush = win32gui.CreateHatchBrush(
                                win32con.HS_VERTICAL, brush_color)

                        old_brush = win32gui.SelectObject(hdc, my_brush)
                    pen = win32gui.CreatePen(
                        win32con.PS_GEOMETRIC, thickness,
                        win32api.RGB(color_r, color_g, color_b))
                    old_pen = win32gui.SelectObject(hdc, pen)

                    if 'center_of_rotation' in r:
                        center_of_rotation_x = r['center_of_rotation'][0]
                        center_of_rotation_y = r['center_of_rotation'][1]
                    else:
                        center_of_rotation_x = 0
                        center_of_rotation_y = 0

                    if angle != 0:
                        r_angle = angle * (math.pi / 180)
                        Py_XFORM = win32gui.GetWorldTransform(hdc)
                        win32gui.SetWorldTransform(
                            hdc, {
                                'M11': math.cos(r_angle),
                                'M12': math.sin(r_angle),
                                'M21': math.sin(r_angle) * -1,
                                'M22': math.cos(r_angle),
                                'Dx': x,
                                'Dy': y
                            })
                        x, y = -center_of_rotation_x, -center_of_rotation_y

                    if 'text_format' in r:
                        text_format = eval(r['text_format'])
                    else:
                        text_format = win32con.DT_CENTER | win32con.DT_SINGLELINE | win32con.DT_VCENTER

                    if 'geometry' in r:
                        if r['geometry'] is Shape.rectangle:
                            win32gui.Rectangle(hdc, int(round(x)),
                                               int(round(y)),
                                               int(round(x + width)),
                                               int(round(y + height)))
                        elif r['geometry'] is Shape.ellipse:
                            win32gui.Ellipse(hdc, int(round(x)), int(round(y)),
                                             int(round(x + width)),
                                             int(round(y + height)))
                        elif r['geometry'] is Shape.arrow:
                            a = thickness
                            t = ((x - int(a * 1.4), y), (x - a * 4, y + a * 3),
                                 (x, y), (x - a * 4, y - a * 3),
                                 (x - int(a * 1.4), y), (x - a * 9, y))
                            win32gui.Polyline(hdc, t)
                        elif r['geometry'] is Shape.image:
                            hicon = r['hicon']
                            win32gui.DrawIconEx(hdc, x, y, hicon, 0, 0, 0,
                                                None, 0x0003)
                        elif r['geometry'] is Shape.triangle and thickness > 0:
                            t = ()
                            for xyrgb in xyrgb_array:
                                t = t + ((int(round(
                                    xyrgb[0])), +int(round(xyrgb[1]))), )
                            t = t + ((int(round(xyrgb_array[0][0])),
                                      int(round(xyrgb_array[0][1]))), )
                            win32gui.Polyline(hdc, t)
                        if angle != 0:
                            win32gui.SetWorldTransform(hdc, Py_XFORM)
                        win32gui.SelectObject(hdc, old_pen)

                    if 'brush' in r and width > 1 and height > 1:
                        win32gui.SelectObject(hdc, old_brush)

                    if 'text' in r:
                        text = r['text']
                        lf = win32gui.LOGFONT()
                        lf.lfFaceName = font_name
                        lf.lfHeight = font_size
                        lf.lfWeight = win32con.FW_NORMAL
                        lf.lfQuality = win32con.ANTIALIASED_QUALITY
                        hf = win32gui.CreateFontIndirect(lf)
                        old_font = win32gui.SelectObject(hdc, hf)

                        if 'text_color' in r:
                            text_color_r = r['text_color'][0]
                            text_color_g = r['text_color'][1]
                            text_color_b = r['text_color'][2]
                        else:
                            text_color_r = 0
                            text_color_g = 0
                            text_color_b = 0
                        win32gui.SetTextColor(
                            hdc,
                            win32api.RGB(text_color_r, text_color_g,
                                         text_color_b))

                        if 'text_bg_color' in r:
                            text_bg_color_r = r['text_bg_color'][0]
                            text_bg_color_g = r['text_bg_color'][1]
                            text_bg_color_b = r['text_bg_color'][2]
                        else:
                            text_bg_color_r = brush_color_r
                            text_bg_color_g = brush_color_g
                            text_bg_color_b = brush_color_b
                        win32gui.SetBkMode(hdc, win32con.TRANSPARENT)
                        win32gui.SetBkColor(
                            hdc,
                            win32api.RGB(text_bg_color_r, text_bg_color_g,
                                         text_bg_color_b))
                        tuple_r = tuple([
                            int(round(x)),
                            int(round(y)),
                            int(round(x + width)),
                            int(round(y + height))
                        ])
                        win32gui.DrawTextW(hdc, text, -1, tuple_r, text_format)
                        win32gui.SelectObject(hdc, old_font)
                win32gui.EndPaint(h_wnd, paint_struct)
                return 0
            else:
                return win32gui.DefWindowProc(h_wnd, message, w_param, l_param)
Пример #10
0
# The OLE automation code uses the Win32com package.  It allows you to
# access Excel just like you were using Visual Basic.  See the web site at
# http://starship.python.net/crew/pirx/spam7/ for more details os using OLE
# automation from Python.
#

import natlink
from natlink.natlinkutils import *

import string
import win32api
import win32com.client
consts = win32com.client.constants

colorMap = {
    'black':win32api.RGB(0,0,0),
    'dark red':win32api.RGB(128,0,0),
    'dark green':win32api.RGB(0,128,0),
    'dark yellow':win32api.RGB(128,128,0),
    'dark blue':win32api.RGB(0,0,128),
    'dark magenta':win32api.RGB(128,0,128),
    'dark cyan':win32api.RGB(0,128,128),
    'dark gray':win32api.RGB(128,128,128),
    'light gray':win32api.RGB(192,192,192),
    'light red':win32api.RGB(255,0,0),
    'light green':win32api.RGB(0,255,0),
    'light yellow':win32api.RGB(255,255,0),
    'light blue':win32api.RGB(0,0,255),
    'light magenta':win32api.RGB(255,0,255),
    'light cyan':win32api.RGB(0,255,255),
    'white':win32api.RGB(255,255,255),
Пример #11
0
WIN = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("BCI Menus")


def Image(Image, width, height, x, y):
    Resized = pygame.transform.smoothscale(Image, (width, height))
    WIN.blit(Resized, (x, y))


# Set window transparency color
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(
    hwnd, win32con.GWL_EXSTYLE,
    win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*TRAN), 0,
                                    win32con.LWA_COLORKEY)

# Set window transparency colour
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*TRAN), 0,
                                    win32con.LWA_COLORKEY)


def draw_text(text, font, colour, surface, x, y):
    textobj = font.render(text, 1, colour)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)


def draw_window():
Пример #12
0
while first_key != "ctrl":
    first_key = keyboard.read_key()
    print("waiting for the keys")
playsound(directory + "first_click.wav", block=False)
print(first_key, "pressed (first key)")
firstx, firsty = pyautogui.position()
time.sleep(0.3)
second_key = keyboard.read_key()
while second_key != "ctrl" and second_key != "alt" and second_key != "shift":
    second_key = keyboard.read_key()
    print("waiting for the keys")
print(second_key, "pressed (second key)")
playsound(directory + "second_click.wav", block=False)
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
dc = win32gui.GetDC(0)
red = win32api.RGB(255, 0, 0)
x, y = pyautogui.position()
if x < firstx:
    tempx, tempy = x, y
    x, y = firstx, firsty
    firstx = tempx
    firsty = tempy
    print("replaced x and y")
try:
    im = PIL.ImageGrab.grab(bbox=(firstx, firsty, x, y))
except:
    im = PIL.ImageGrab.grab(bbox=(x, y, firstx, firsty))
for num1 in range(35):
    for num in range(firsty, y):
        win32gui.SetPixel(dc, firstx - 1, num, red)
        win32gui.SetPixel(dc, firstx - 2, num, red)
Пример #13
0
def win32_color(color):
    if isinstance(color, (tuple, list)):
        return win32api.RGB(*color)
Пример #14
0
pygame.init()
info = pygame.display.Info()
w = info.current_w
h = info.current_h
screen = pygame.display.set_mode((w, h), pygame.NOFRAME) # For borderless, use pygame.NOFRAME
done = False
fuchsia = (255, 0, 128)  # Transparency color

# Create layered window
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                       win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
# Set window transparency color
# win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 50, win32con.LWA_ALPHA)

click1 = 0
x1 = 0
y1 = 0
x2 = 0
y2 = 0
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                done = True

        if event.type == pygame.MOUSEBUTTONDOWN:
Пример #15
0
# These styles _always_ have this specific style number, regardless of
# internal or external formatter.
SPECIAL_STYLES = [
    (STYLE_BRACE, (0, 0, 200, 0, 0x000000), 0xffff80,
     scintillacon.STYLE_BRACELIGHT),
    (STYLE_BRACEBAD, (0, 0, 200, 0, 0x000000), 0x8ea5f2,
     scintillacon.STYLE_BRACEBAD),
    (STYLE_LINENUMBER, (0, 0, 200, 0, 0x000000),
     win32api.GetSysColor(win32con.COLOR_3DFACE),
     scintillacon.STYLE_LINENUMBER),
    (STYLE_INDENTGUIDE, (0, 0, 200, 0, 0x000000), CLR_INVALID,
     scintillacon.STYLE_INDENTGUIDE),
    # Not actually a style; requires special handling to send appropriate
    # messages to scintilla
    (STYLE_SELECTION, (0, 0, 200, 0, CLR_INVALID),
     win32api.RGB(0xc0, 0xc0, 0xc0), 999999),
]

PythonSampleCode = """\
# Some Python
class Sample(Super):
  def Fn(self):
\tself.v = 1024
dest = 'dest.html'
x = func(a + 1)|)
s = "I forget...
## A large
## comment block"""


class PythonSourceFormatter(Formatter):
Пример #16
0
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


screen = pygame.display.set_mode((screen_width, screen_height))
done = False
transparent = (255, 0, 128)
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(
    hwnd, win32con.GWL_EXSTYLE,
    win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*transparent), 0,
                                    win32con.LWA_COLORKEY)
pressed_keys = []
launched = False

while not done:
    if launched:

        # Mouse positioning
        (x_mouse, y_mouse) = pygame.mouse.get_pos()
        mapping_col = int(x_mouse // (screen_width / 3))
        mapping_line = int(y_mouse // (screen_height / 3))

        # GUI
        pygame.draw.rect(screen, background_color,
                         pygame.Rect(0, 0, screen_width, screen_height))
Пример #17
0
 def DoPaint(self, dc):
     rc = self.GetClientRect()
     br = Sdk.CreateBrush(win32con.BS_SOLID, win32api.RGB(255, 0, 0), 0)
     dc.FrameRectFromHandle(rc, br)
     Sdk.DeleteObject(br)
Пример #18
0
from vsc import vsc_hotkeys

#itr = iter(vsc_hotkeys)
itr = iter(hotkeys)

pygame.init()
screen = pygame.display.set_mode((250, 100)) # For borderless, use pygame.NOFRAME
pygame.display.set_caption('')
fuchsia = (255, 0, 128)  # Transparency color
dark_red = (139, 100, 0)

# Set window transparency color
hwnd = pygame.display.get_wm_info()["window"]
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                       win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY)


f1 = pygame.font.Font(None, 36)
text1 = f1.render('', 1, (180, 0, 0))
screen.blit(text1, (10, 50))

while 1:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            exit()
        if i.type == pygame.MOUSEBUTTONDOWN:
            text1 = f1.render(next(itr), 1, (180, 200, 30))

    screen.fill(fuchsia)  # Transparent background
    pygame.draw.rect(screen, dark_red, pygame.Rect(30, 30, 60, 60))
Пример #19
0
import math

import win32api
import win32con
import win32gui

from GLHF.libs.datatypes import matrix
from GLHF.libs.datatypes import vector

COLOR_RED = win32api.RGB(255, 0, 0)
COLOR_GREEN = win32api.RGB(0, 255, 0)
COLOR_BLUE = win32api.RGB(0, 0, 255)
COLOR_YELLOW = win32api.RGB(255, 215, 10)

MAX_TEXT_WIDTH = 150
MAX_TEXT_HEIGHT = 20


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)
class ImageRegionTool(SelectorToolBase):
    """Draw a selection rectangle and return the coordinates.
    Optionally save the region as an image file.
    """

    REGION_WIDTH = 3
    REGION_COLOR = win32api.RGB(255, 0, 0)

    def __init__(self, filename=None, timeout=30):
        super().__init__(timeout)
        self.filename = filename
        self._selection_start = None
        self._selection = None

    @property
    def message_map(self):
        return {
            win32con.WM_LBUTTONDOWN: self.on_lbuttondown,
            win32con.WM_MOUSEMOVE: self.on_mousemove,
            win32con.WM_LBUTTONUP: self.on_lbuttonup,
            win32con.WM_KEYDOWN: self.on_keydown,
            win32con.WM_PAINT: self.on_paint,
        }

    @property
    def result(self):
        return self._selection

    def _save_selection(self):
        """Save selection region from the original screenshot."""
        assert self.filename is not None
        assert self._selection is not None

        left, top, right, bottom = self._selection
        width = right - left
        height = bottom - top

        src_dch = win32gui.CreateCompatibleDC(None)
        src_dc = win32ui.CreateDCFromHandle(src_dch)

        src_default = src_dc.SelectObject(self._screenshot)
        assert src_default is not None

        dst_dch = win32gui.CreateCompatibleDC(None)
        dst_dc = win32ui.CreateDCFromHandle(dst_dch)

        dst_bitmap = win32ui.CreateBitmap()
        dst_bitmap.CreateCompatibleBitmap(src_dc, width, height)

        dst_default = dst_dc.SelectObject(dst_bitmap)
        assert dst_default is not None

        dst_dc.BitBlt((0, 0), (width, height), src_dc, (left, top),
                      win32con.SRCCOPY)

        dst_bitmap.SaveBitmapFile(dst_dc, self.filename)
        self.logger.info("Saved selected region as '%s'", self.filename)

        dst_dc.SelectObject(dst_default)
        src_dc.SelectObject(src_default)

        win32gui.DeleteObject(dst_bitmap.GetHandle())
        dst_dc.DeleteDC()
        src_dc.DeleteDC()

    def on_lbuttondown(self, hwnd, message, wparam, lparam):
        """Left button being pressed starts new selection."""
        self._selection_start = lparam_to_point(lparam)
        self._selection = None

        # Force re-draw
        win32gui.InvalidateRect(hwnd, None, True)
        return 0

    def on_mousemove(self, hwnd, message, wparam, lparam):
        """Update selection region with mouse location."""
        # Only update region while left button is pressed
        if not wparam & win32con.MK_LBUTTON:
            return 0

        x1, y1 = self._selection_start
        x2, y2 = lparam_to_point(lparam)

        # Handle drawing region from bottom-right to top-left
        self._selection = [min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)]

        # Force re-draw
        win32gui.InvalidateRect(hwnd, None, True)
        return 0

    def on_lbuttonup(self, hwnd, message, wparam, lparam):
        """Selection is finished when left button is no longer pressed."""
        if self.filename and self._selection:
            self._save_selection()

        self.stop()
        return 0

    def on_keydown(self, hwnd, message, wparam, lparam):
        """Cancel selection with escape key."""
        if wparam == win32con.VK_ESCAPE:
            self._selection = None
            self.stop()
        return 0

    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
Пример #21
0
import win32api
import win32con
import win32ui
import copy
import string
from . import scintillacon

# Used to indicate that style should use default color
from win32con import CLR_INVALID

######################################################
# Property Page for syntax formatting options

# The standard 16 color VGA palette should always be possible
paletteVGA = (
    ("Black", win32api.RGB(0, 0, 0)),
    ("Navy", win32api.RGB(0, 0, 128)),
    ("Green", win32api.RGB(0, 128, 0)),
    ("Cyan", win32api.RGB(0, 128, 128)),
    ("Maroon", win32api.RGB(128, 0, 0)),
    ("Purple", win32api.RGB(128, 0, 128)),
    ("Olive", win32api.RGB(128, 128, 0)),
    ("Gray", win32api.RGB(128, 128, 128)),
    ("Silver", win32api.RGB(192, 192, 192)),
    ("Blue", win32api.RGB(0, 0, 255)),
    ("Lime", win32api.RGB(0, 255, 0)),
    ("Aqua", win32api.RGB(0, 255, 255)),
    ("Red", win32api.RGB(255, 0, 0)),
    ("Fuchsia", win32api.RGB(255, 0, 255)),
    ("Yellow", win32api.RGB(255, 255, 0)),
    ("White", win32api.RGB(255, 255, 255)),
Пример #22
0
def RGB(l):
    return win32api.RGB(l[0], l[1], l[2])
Пример #23
0
 def OnPrepareDC(self, dc, printinfo):
     # Set up the DC for forthcoming OnDraw call
     dc.SetTextColor(win32api.RGB(0, 0, 255))
     dc.SetBkColor(win32api.GetSysColor(win32con.COLOR_WINDOW))
     dc.SelectObject(self.font)
     dc.SetTextAlign(win32con.TA_CENTER | win32con.TA_BASELINE)
Пример #24
0
                    continue
                zet = True
                cm.append(i)
        if not zet:
            continue
        zet = False
        if cm:
            im = choice(cm)
        else:
            warn = True
            break

        ps = im[3] if ps != im[3] else im[4]
        mrun.append(im)

    #
    if warn:
        continue

    als = []
    for i in mrun:
        als.append(i[0])
    als = ','.join(als)
    print(als)
    create_grid(grid_mass)
    for ii in mrun:
        for i in ii[1]:
            win32gui.SetPixel(dc, i[0], i[1], win32api.RGB(255, 0, 0))
        sleep(0.07)
    sleep(2)
Пример #25
0
 def __init__(self):
     hierlist.HierListWithItems.__init__(self, None,
                                         win32ui.IDB_DEBUGGER_HIER, None,
                                         win32api.RGB(255, 0, 0))
Пример #26
0
def create_grid(grid_mass):
    for i in grid_mass:
        win32gui.SetPixel(dc, i[0], i[1], win32api.RGB(64, 0, 0))
Пример #27
0
def main():
    global smallFont, basicFont, pygame, config, color_file
    # load env variables
    load_dotenv(str(filePath.joinpath('.env')))
    config = loadConfig()
    color_file.loadColors(filePath)

    # set up pygame
    pygame.display.init()
    pygame.font.init()

    # set up fonts
    fontFile = str(filePath.joinpath('fonts/RobotoMono-Medium.ttf'))

    smallFont = pygame.font.Font(fontFile, config['lyric_fontsize'])
    basicFont = pygame.font.Font(fontFile, config['title_fontsize'])

    renderer.setFont(smallFont)

    displayInfo = pygame.display.Info()
    width, height = displayInfo.current_w, displayInfo.current_h
    # set up the window
    if config['startSize']['w'] > 0 and config['startSize']['h'] > 0:
        width = config['startSize']['w']
        height = config['startSize']['h']
    # set window positionsurfa
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (
        config['startPosition']['x'], config['startPosition']['y'])
    if config['startCentered']:
        os.environ['SDL_VIDEO_CENTERED'] = "1"
    windowSurface = createMainSurface(width, height)
    # reset value so it doesn't get used when resizing the window later
    os.environ['SDL_VIDEO_WINDOW_POS'] = ""
    os.environ['SDL_VIDEO_CENTERED'] = ''
    pygame.event.post(
        pygame.event.Event(pygame.VIDEORESIZE, {
            'w': width,
            'h': height
        }))

    titlePos = (20, 20)
    artistPos = (20, 50)
    coverPos = (20, 100)
    coverImgSize = (config['cover_image_size']['w'],
                    config['cover_image_size']['h'])
    controlsPos = (20, coverPos[1] + coverImgSize[1] + 10)
    volumeSliderPos = (20, controlsPos[1] + 100 + 5)
    devicesSelectorPos = (20, volumeSliderPos[1] + 30)
    recentlyPlayedSongsPos = (0, 30)  #x position will get calculated later

    controls_renderer = controlsRenderer.ControlsRenderer(
        color_file, coverImgSize[0])
    volume_slider_renderer = sliderRenderer.SliderRenderer(
        color_file, 0.5, coverImgSize[0])
    recent_songs_font = pygame.font.Font(fontFile, 14)
    recent_songs_renderer = recentSongsRenderer.RecentSongsRenderer(
        color_file, 50, width - coverImgSize[0], recent_songs_font)

    device_font = pygame.font.Font(fontFile, 14)
    device_selector_renderer = devices_renderer.DeviceSelectorRenderer(
        color_file, coverImgSize[0], height - devicesSelectorPos[1],
        device_font)

    if sys.platform == 'win32':
        if config['transparentBackground']:
            hwnd = pygame.display.get_wm_info()["window"]
            win32gui.SetWindowLong(
                hwnd, win32con.GWL_EXSTYLE,
                win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
                | win32con.WS_EX_LAYERED)
            win32gui.SetLayeredWindowAttributes(
                hwnd, win32api.RGB(*color_file.getColor('BACKGROUND')), 0,
                win32con.LWA_COLORKEY)

    pygame.display.set_caption('Spotify Lyric Screen')
    pygame.mouse.set_visible(config['show_mouse_cursor'])

    # set up the text
    textSong = None
    textArtists = None
    textLyric = None

    oldSongName = ""

    start = time.time()
    interval = 3
    nextCheck = start + 1

    # run the game loop
    startTime = 0
    timepassed_ms = 0
    isPlaying = False
    songLength = 300
    device_info = None

    ratio = 0
    songActive = False
    coverImg = None

    timeSongStart = 0
    draggingVolumeSlider = False
    recently_played_songs = None
    albumURI = ""
    album = None
    while True:
        # draw the white background onto the surface
        windowSurface.fill(color_file.getColor('BACKGROUND'))
        controlsSurface = controls_renderer.renderToSurface()
        windowSurface.blit(controlsSurface, controlsPos)
        volumeSurface = volume_slider_renderer.renderToSurface()
        windowSurface.blit(volumeSurface, volumeSliderPos)
        deviceSelectorSurface = device_selector_renderer.renderToSurface(
            isPlaying)
        windowSurface.blit(deviceSelectorSurface, devicesSelectorPos)

        recentlyPlayedSongsSurface = recent_songs_renderer.renderToSurface()
        windowSurface.blit(recentlyPlayedSongsSurface, recentlyPlayedSongsPos)
        if time.time() >= nextCheck:
            nextCheck += interval
            newSongName, songLength, songImgURl, albumURI = spotify.getSong()

            if newSongName == "":
                songActive = False
                print("[Updated] No song playing...")
            elif oldSongName != newSongName:
                oldSongName = newSongName
                songActive = True
                # TODO: request data in seperate thread so the program doesn't freeze
                textSong = basicFont.render(
                    newSongName, True, color_file.getColor('player.title'),
                    None)
                textArtists = basicFont.render(
                    spotify.getArtists(), True,
                    color_file.getColor('player.artist'), None)
                lyrics = genius.getLyric(newSongName, spotify.getFirstArtist())
                renderer.setLyric(lyrics)
                if songImgURl:
                    imgPath = str(filePath.joinpath('coverImg.jpg'))
                    urllib.request.urlretrieve(songImgURl, imgPath)
                    coverImg = pygame.image.load(imgPath)
                    coverImg = pygame.transform.scale(coverImg, coverImgSize)
                print("[Updated] {}".format(newSongName))
                timeSongStart = time.time()
                if config['showOnTopSlider'] == 'album' and albumURI:
                    album = spotify.get_album(albumURI)
                    if album['album_type'] == 'single':
                        recently_played_songs = spotify.get_recently_played()
                    else:
                        recently_played_songs = album['tracks']['items']
                elif config['showOnTopSlider'] == 'top_tracks':
                    recently_played_songs = spotify.get_top_list()

                if recently_played_songs:
                    recent_songs_renderer.recently_played_songs = recently_played_songs
                recent_songs_renderer.time = 0

                labelWidth = max(titlePos[0] + textSong.get_width(),
                                 artistPos[0] + textArtists.get_width())
                xPos = max(coverPos[0] + coverImgSize[0] + 20, labelWidth)
                minWidth = width - xPos
                recent_songs_renderer.setWidth(minWidth)
                recentlyPlayedSongsPos = (xPos, recentlyPlayedSongsPos[1])
            devices = spotify.getAvailableDevices()
            if devices:
                device_selector_renderer.devices = devices

            startTime, timepassed_ms, isPlaying, device_info = spotify.getCurrentSongInfo(
            )
            controls_renderer.songPlaying = isPlaying
            if device_info:
                current_volume = device_info['volume_percent']
                volume_slider_renderer.currentNormalized = current_volume / 100
        if songActive:
            # TODO: Set fixed framerate
            timeSince = time.time() - timeSongStart
            if isPlaying:
                timepassed_ms += timeSince * 1000
            timeSongStart = time.time()
            # draw the text onto the surface
            windowSurface.blit(textSong, titlePos)
            windowSurface.blit(textArtists, artistPos)

            #generate the lyric surface and draw it
            ratio = timepassed_ms / songLength
            heightOffset = height / 2 - renderer.height / 1 * ratio
            lyricSurface = renderer.renderToSurface(
                Rect(0, artistPos[1] + basicFont.get_height() - heightOffset,
                     renderer.width, height - 120))
            windowSurface.blit(
                lyricSurface,
                (coverPos[0] + coverImgSize[0] + 20, heightOffset))

            #draw the album cover image
            if coverImg:
                windowSurface.blit(coverImg, coverPos)

            #draw the progress bar
            playingbarRect = Rect(20, height - 20, width - 40, 6)
            pygame.draw.rect(
                windowSurface,
                color_file.getColor('player.playingbar.background'),
                playingbarRect)
            currentRect = Rect(playingbarRect.left, playingbarRect.top,
                               playingbarRect.width * ratio,
                               playingbarRect.height)
            pygame.draw.rect(windowSurface,
                             color_file.getColor('player.playingbar'),
                             currentRect)
        else:
            textSong = basicFont.render("No song playing...", True,
                                        color_file.getColor('player.lyrics'),
                                        None)
            windowSurface.blit(textSong, titlePos)

        # update the window
        pygame.display.update()

        #handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.display.quit()
                sys.exit(0)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.display.quit()
                    sys.exit(0)
            elif event.type == pygame.VIDEORESIZE:
                width = event.w
                height = event.h
                playingbarRect = Rect(2, 2, width - 4, 6)
                windowSurface = createMainSurface(width, height)
                renderer.setMaxWidth(width -
                                     (coverPos[0] + coverImgSize[0] + 20 + 80))
            elif event.type == pygame.MOUSEMOTION:
                if draggingVolumeSlider:
                    volume_slider_renderer.update_value(mouse_pos[0])
                if songActive:
                    mouse_pos = (event.pos[0] - controlsPos[0],
                                 event.pos[1] - controlsPos[1])
                    controls_renderer.highlightPlaybutton = controls_renderer.playButtonRect.collidepoint(
                        mouse_pos)
                    controls_renderer.highlightPreviousbutton = controls_renderer.previousButtonRect.collidepoint(
                        mouse_pos)
                    controls_renderer.highlightNextbutton = controls_renderer.nextButtonRect.collidepoint(
                        mouse_pos)

                    mouse_pos = (event.pos[0] - recentlyPlayedSongsPos[0],
                                 event.pos[1] - recentlyPlayedSongsPos[1])
                    highlightedBoxIndex = -1
                    hitBox = recent_songs_renderer.checkMouseHit(mouse_pos)
                    if hitBox:
                        if 'index' in hitBox:
                            highlightedBoxIndex = hitBox['index']
                    recent_songs_renderer.highlightedIdx = highlightedBoxIndex
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if not draggingVolumeSlider:
                    mouse_pos = (event.pos[0] - volumeSliderPos[0],
                                 event.pos[1] - volumeSliderPos[1])
                    if volume_slider_renderer.borderRect.collidepoint(
                            mouse_pos):
                        volume_slider_renderer.update_value(mouse_pos[0])
                        draggingVolumeSlider = True
                if not draggingVolumeSlider and songActive:
                    if device_info:
                        mouse_pos = (event.pos[0] - controlsPos[0],
                                     event.pos[1] - controlsPos[1])
                        if controls_renderer.playButtonRect.collidepoint(
                                mouse_pos):
                            spotify.pauseOrResumeSong(device_info['id'],
                                                      isPlaying)
                            isPlaying = not isPlaying
                            controls_renderer.songPlaying = isPlaying
                        elif controls_renderer.previousButtonRect.collidepoint(
                                mouse_pos):
                            spotify.nextOrPreviousSong(True)
                        elif controls_renderer.nextButtonRect.collidepoint(
                                mouse_pos):
                            spotify.nextOrPreviousSong(False)
            elif event.type == pygame.MOUSEBUTTONUP:
                if draggingVolumeSlider:
                    mouse_pos = (event.pos[0] - volumeSliderPos[0],
                                 event.pos[1] - volumeSliderPos[1])
                    volume = volume_slider_renderer.currentNormalized * 100
                    if device_info:
                        spotify.setCurrentVolume(volume, device_info['id'])
                    draggingVolumeSlider = False
                else:
                    mouse_pos = (event.pos[0] - devicesSelectorPos[0],
                                 event.pos[1] - devicesSelectorPos[1])
                    for device in device_selector_renderer.devices:
                        if 'hitbox' in device:
                            if device['hitbox'].collidepoint(mouse_pos):
                                spotify.set_to_device(device)

                    mouse_pos = (event.pos[0] - recentlyPlayedSongsPos[0],
                                 event.pos[1] - recentlyPlayedSongsPos[1])
                    clicked_box = recent_songs_renderer.checkMouseHit(
                        mouse_pos)
                    if clicked_box:
                        recent_songs_renderer.boxClicked(
                            clicked_box, event.button)
Пример #28
0
height = win32api.GetSystemMetrics(1)  #Getting computers resolution height
screen = pygame.display.set_mode(
    (width, height), pygame.NOFRAME
)  #Creating our screen, setting it to NOFRAME so we dont see the windows default UI (Minimize, Fullscreen, Exit)

fuchsia = (255, 0, 128)  # Transparency color

# Set window transparency color
hwnd = pygame.display.get_wm_info()["window"]

win32gui.SetWindowLong(
    hwnd, win32con.GWL_EXSTYLE,
    win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(
    hwnd, win32api.RGB(*fuchsia), 0,
    win32con.LWA_COLORKEY)  #Setting window color to transparent
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                      win32con.SWP_NOSIZE)  #Setting window to always be on top

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit(0)
    screen.fill(
        fuchsia
    )  #Setting the screen blank every frame so that the drawings will update in realtime

    #drawing loop
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(0, 0, 60, 60))  #Example
    #end drawing loop
Пример #29
0
    def setup(self, alpha=0xff):
        global hWnd, hDC, hRC, hbitmap

        hwnd = pygame.display.get_wm_info()["window"]
        if SOFTWARE_RENDER:
            hWnd = pygame.display.get_wm_info()["window"]

            hdcwnd = win32gui.GetDC(hWnd)
            hDC = win32gui.CreateCompatibleDC(hdcwnd)

            win32gui.SetWindowLong(
                hWnd, win32con.GWL_EXSTYLE,
                win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
                | win32con.WS_EX_LAYERED)

            bmi = BITMAPINFO()
            bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
            bmi.bmiHeader.biWidth = self.WIDTH
            bmi.bmiHeader.biHeight = self.HEIGHT
            bmi.bmiHeader.biPlanes = 1
            bmi.bmiHeader.biBitCount = 32
            bmi.bmiHeader.biCompression = win32con.BI_RGB
            bmi.bmiHeader.biSizeImage = self.WIDTH * self.HEIGHT * 4
            hbitmap = ctypes.windll.gdi32.CreateDIBSection(
                hDC, ctypes.byref(bmi), win32con.DIB_RGB_COLORS,
                ctypes.byref(ctypes.c_void_p()), None, 0)
            win32gui.SelectObject(hDC, hbitmap)

            PFD_TYPE_RGBA = 0
            PFD_MAIN_PLANE = 0
            PFD_DRAW_TO_BITMAP = 0x00000008
            PFD_SUPPORT_GDI = 0x00000010
            PFD_SUPPORT_OPENGL = 0x00000020

            dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI

            pfd = PIXELFORMATDESCRIPTOR()
            pfd.nSize = ctypes.sizeof(PIXELFORMATDESCRIPTOR)
            pfd.nVersion = 1
            pfd.dwFlags = dwFlags
            pfd.iPixelType = PFD_TYPE_RGBA
            pfd.cColorBits = 32
            pfd.cDepthBits = 32
            pfd.cStencilBits = 8
            pfd.iLayerType = PFD_MAIN_PLANE

            # hdc = win32gui.GetDC(hWnd)
            pixelformat = ChoosePixelFormat(hDC, pfd)
            SetPixelFormat(hDC, pixelformat, pfd)
            hRC = wglCreateContext(hDC)
            # win32gui.ReleaseDC(hWnd, hdc)
            wglMakeCurrent(hDC, hRC)

            win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)
            win32gui.SetWindowPos(
                hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE)

            cur_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
            win32gui.SetWindowLong(
                hwnd, win32con.GWL_EXSTYLE, cur_style
                | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED)
        else:
            win32gui.SetWindowLong(
                hwnd, win32con.GWL_EXSTYLE,
                win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
                | win32con.WS_EX_LAYERED | win32con.WS_EX_TOOLWINDOW)
            win32gui.SetParent(hwnd, win32con.NULL)
            win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*COLORKEY),
                                                0, win32con.LWA_COLORKEY)

            win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)
            win32gui.SetWindowPos(
                hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE)

            cur_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
            win32gui.SetWindowLong(
                hwnd, win32con.GWL_EXSTYLE, cur_style
                | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED)
Пример #30
0
# Drawing red squares (or QR codes) for calibration
msize = 300  # marker size
height, width, channels = res.shape

y_offset = height - msize
x_offset = width - msize

tl = cv2.resize(marker0, (msize, msize), interpolation=cv2.INTER_NEAREST)
res[0:0 + tl.shape[0], 0:0 + tl.shape[1]] = tl
res[0:0 + tl.shape[0], x_offset:x_offset + tl.shape[1]] = tl
res[y_offset:y_offset + tl.shape[0], 0:0 + tl.shape[1]] = tl
res[y_offset:y_offset + tl.shape[0], x_offset:x_offset + tl.shape[1]] = tl

cv2.namedWindow("Squares Overlay", cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("Squares Overlay", cv2.WND_PROP_FULLSCREEN,
                      cv2.WINDOW_FULLSCREEN)
cv2.imshow("Squares Overlay", res)

hwnd = win32gui.FindWindow(None, "Squares Overlay")
win32gui.SetWindowLong(
    hwnd, win32con.GWL_EXSTYLE,
    win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) |
    win32con.WS_EX_LAYERED)  # no idea, but it goes together with transparency
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(
    0, 255, 0), 0, win32con.LWA_COLORKEY)  # black as transparent
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, -5, -5, GetSystemMetrics(0),
                      GetSystemMetrics(1), 0)  # always on top
win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)  # maximiced

cv2.waitKey(-1)