Python win32 api drawText() 和 SetTextColor

Python win32 api drawText() and SetTextColor

我设法拼凑了一个程序,该程序在多行上接收字符串并将它们打印到透明背景上。我想知道是否有办法为字符串的各个部分涂上不同的颜色。我知道有,但我对 win32 的不了解确实妨碍了我的工作。我需要将文本分成两部分并调用 drawText() 还是可以在字符串中途更改文本颜色?任何关于信息或解决方案的观点都会很棒。

示例:字符串 = "Username: some message that the user has sent."

我已经在 Stack 和其他多个网站上进行了搜索,但到目前为止还没有找到满意的结果。 我通常不会,但我已经转储了代码,因为它可以是 运行 你可以明白我的意思。

对于缺少评论和代码状态,我提前表示歉意。

import win32api
import win32con
import win32gui
import time
import threading
from collections import deque


userAndMessage = deque()

def queue(message):
    userAndMessage.append(message)

def getQueue():
    return userAndMessage;

def dequeue():
    return userAndMessage.popleft()

def cleanMessage(message):
    return message.split("\r\n")[0]

def showMessages():
    return userAndMessage[0] + "\n" + userAndMessage[1] + "\n" + 
userAndMessage[2] + "\n" + userAndMessage[3] + "\n" + userAndMessage[4]

#Code example modified from:
#Christophe Keller
#Hello World in Python using Win32

windowText = ''

def main():
    #get instance handle
    hInstance = win32api.GetModuleHandle()
    # the class name
    className = 'SimpleWin32'

    # create and initialize window class
    wndClass                = win32gui.WNDCLASS()
    wndClass.style          = win32con.CS_HREDRAW | win32con.CS_VREDRAW
    wndClass.lpfnWndProc    = wndProc
    wndClass.hInstance      = hInstance
    wndClass.hCursor        = win32gui.LoadCursor(None, win32con.IDC_ARROW)
    wndClass.hbrBackground  = win32gui.GetStockObject(win32con.WHITE_BRUSH)
    wndClass.lpszClassName  = className

    # register window class
    wndClassAtom = None
    try:
        wndClassAtom = win32gui.RegisterClass(wndClass)
    except Exception as e:
        print (e)
        raise e

    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | 
win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | 
win32con.WS_EX_TRANSPARENT
    style = win32con.WS_DISABLED | win32con.WS_POPUP | win32con.WS_VISIBLE

    hWindow = win32gui.CreateWindowEx(
        exStyle,
        wndClassAtom,
        None, # WindowName
        style,
        20, # x
        900, # y
        1920, # width
        600, # height
        None, # hWndParent
        None, # hMenu
        hInstance,
        None # lpParam
)

    # Show & update the window
    win32gui.SetLayeredWindowAttributes(hWindow, 0x00ffffff, 255, 
win32con.LWA_COLORKEY | win32con.LWA_ALPHA)
    win32gui.SetWindowPos(hWindow, win32con.HWND_TOPMOST, 0, 0, 0, 0,
        win32con.SWP_NOACTIVATE | win32con.SWP_NOMOVE | win32con.SWP_NOSIZE 
| win32con.SWP_SHOWWINDOW)

    win32gui.ShowWindow(hWindow, win32con.SW_SHOWNORMAL)
    win32gui.UpdateWindow(hWindow)

    # New code: Create and start the thread
    thr = threading.Thread(target=customDraw, args=(hWindow,))
    thr.setDaemon(False)
    thr.start()

    # Dispatch messages
    win32gui.PumpMessages()


# New code: Attempt to change the text 1 second later
def customDraw(hWindow): 

    strOne      = "SomeUser: This is test line one"
    strTwo      = "SomeOtherUser: This is test line two"
    strThree    = "AndAnother: This is test line three"
    strFour     = "UserOne: This is test line four"
    strFive     = "AndAgain: This is test line five" 


    queue(strOne)
    queue(strTwo)
    queue(strThree)
    queue(strFour)
    queue(strFive) 

    global windowText
    windowText = showMessages()
    win32gui.RedrawWindow(hWindow, None, None, win32con.RDW_INVALIDATE | 
win32con.RDW_ERASE)


def wndProc(hWnd, message, wParam, lParam):
    if message == win32con.WM_PAINT:
        hDC, paintStruct = win32gui.BeginPaint(hWnd)


        fontSize = 26
        lf = win32gui.LOGFONT()
        lf.lfFaceName = "Stencil"
        lf.lfHeight = fontSize
        lf.lfWeight = 600

        lf.lfQuality = win32con.NONANTIALIASED_QUALITY
        hf = win32gui.CreateFontIndirect(lf)
        win32gui.SelectObject(hDC, hf)
        win32gui.SetTextColor(hDC,win32api.RGB(240,0,50))

        rect = win32gui.GetClientRect(hWnd)
        win32gui.DrawText(hDC,windowText,-1, rect, win32con.DT_CALCRECT); 
        win32gui.DrawText(
            hDC,
            windowText,
            -1,
            rect,
            win32con.DT_NOCLIP | win32con.DT_VCENTER | 
win32con.DT_EXPANDTABS
        )
        win32gui.EndPaint(hWnd, paintStruct)
        return 0

    elif message == win32con.WM_DESTROY:
        print('Being destroyed')
        win32gui.PostQuitMessage(0)
        return 0

    else:
        return win32gui.DefWindowProc(hWnd, message, wParam, lParam)

if __name__ == '__main__':
    main()

可能有一些缩进不正常,程序中不是这种情况,只是我必须在每行文本上按空格键 4 次。

谢谢

是的,在调用DrawText

之前必须使用SetTextColor来改变颜色

您使用 DT_CALCRECT 选项调用 DrawText 是正确的。这不会绘制任何东西,它只是计算矩形的高度(基于宽度...)Python 的 DrawText 将 return 计算矩形的元组。

然后再次调用 DrawText,使用相同的文本格式,但没有 DT_CALCRECT 标志。然后偏移矩形,改变颜色,绘制下一个文本。

注意,这在 pywin32 中会变得非常混乱,首先在 C/C++ 中尝试可能更容易。

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

    fontSize = 16
    lf = win32gui.LOGFONT()
    lf.lfFaceName = "Stencil"
    lf.lfHeight = fontSize
    lf.lfWeight = 600

    lf.lfQuality = win32con.NONANTIALIASED_QUALITY
    hf = win32gui.CreateFontIndirect(lf)
    win32gui.SelectObject(hDC, hf)

    text1 = 'line1'
    text2 = 'line2'
    text3 = 'line3'
    rect = win32gui.GetClientRect(hWnd)

    textformat = win32con.DT_LEFT | win32con.DT_TOP

    win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
    drawrect = win32gui.DrawText(hDC, text1, -1, rect, textformat | win32con.DT_CALCRECT);
    win32gui.DrawText(hDC, text1, -1, rect, textformat)

    l = drawrect[1][0]
    t = drawrect[1][1]
    r = drawrect[1][2]
    b = drawrect[1][3]
    height = b - t
    rect = (l, t + height, r, b + height)

    win32gui.SetTextColor(hDC,win32api.RGB(0,255,0))
    drawrect = win32gui.DrawText(hDC, text2, -1, rect, textformat | win32con.DT_CALCRECT);
    win32gui.DrawText(hDC, text2, -1, rect, textformat)

    l = drawrect[1][0]
    t = drawrect[1][1]
    r = drawrect[1][2]
    b = drawrect[1][3]
    height = b - t
    rect = (l, t + height, r, b + height)

    win32gui.SetTextColor(hDC,win32api.RGB(0,0,255))
    drawrect = win32gui.DrawText(hDC, text3, -1, rect, textformat | win32con.DT_CALCRECT);
    win32gui.DrawText(hDC, text3, -1, rect, textformat)

    win32gui.EndPaint(hWnd, paintStruct)
    return 0

@Barmak,这是我从你的帮助中得到的代码......我标记你是正确的,如果你没有发布我仍然会为此苦苦挣扎。如果你运行它你可以看到它的工作,你的传奇!

import win32api
import win32con
import win32gui
import time
import threading
from collections import deque



messagePrompt = ' :'
userAndMessage = deque()

def queue(message):
    userAndMessage.append(message)

def getQueue():
    return userAndMessage;

def dequeue():
    return userAndMessage.popleft()

def cleanMessage(message):
    return message.split("\r\n")[0]

def showMessages():
    return userAndMessage[0] + "\n" + userAndMessage[1] + "\n" + userAndMessage[2] + 
"\n" + userAndMessage[3] + "\n" + userAndMessage[4]


#Code example modified from:
#Christophe Keller
#Hello World in Python using Win32

# New code: Define globaL
def main():
    #get instance handle
    hInstance = win32api.GetModuleHandle()
    # the class name
    className = 'SimpleWin32'

    # create and initialize window class
    wndClass                = win32gui.WNDCLASS()
    wndClass.style          = win32con.CS_HREDRAW | win32con.CS_VREDRAW
    wndClass.lpfnWndProc    = wndProc
    wndClass.hInstance      = hInstance
    wndClass.hCursor        = win32gui.LoadCursor(None, win32con.IDC_ARROW)
    wndClass.hbrBackground  = win32gui.GetStockObject(win32con.WHITE_BRUSH)
    wndClass.lpszClassName  = className

    # register window class
    wndClassAtom = None
    try:
        wndClassAtom = win32gui.RegisterClass(wndClass)
    except Exception as e:
        print (e)
        raise e

    exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | 
win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT
    style = win32con.WS_DISABLED | win32con.WS_POPUP | win32con.WS_VISIBLE

    hWindow = win32gui.CreateWindowEx(
        exStyle,
        wndClassAtom,
        None, # WindowName
        style,
        20, # x
        900, # y
        1920, # width
        600, # height
        None, # hWndParent
        None, # hMenu
        hInstance,
        None # lpParam
    )

    # Show & update the window
    win32gui.SetLayeredWindowAttributes(hWindow, 0x00ffffff, 255, 
win32con.LWA_COLORKEY | win32con.LWA_ALPHA)
    win32gui.SetWindowPos(hWindow, win32con.HWND_TOPMOST, 0, 0, 0, 0,
        win32con.SWP_NOACTIVATE | win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | 
win32con.SWP_SHOWWINDOW)

    win32gui.ShowWindow(hWindow, win32con.SW_SHOWNORMAL)
    win32gui.UpdateWindow(hWindow)

    thr = threading.Thread(target=customDraw, args=(hWindow,))
    thr.setDaemon(False)
    thr.start()

    # Dispatch messages
    win32gui.PumpMessages()

def customDraw(hWindow):
    win32gui.RedrawWindow(hWindow, None, None, win32con.RDW_INVALIDATE | 
win32con.RDW_ERASE)



queue(("Dave: ", "Daves message was important"))
queue(("Chris: ", "Chris is asleep again"))
queue(("Suzy: ", "Suzy has had way to much cake"))
queue(("Sarah: ", "Sarah is shockingly beautiful"))
queue(("Steve: ", "Steve likes to eat dog treats")) 


def wndProc(hWnd, message, wParam, lParam):
    textFormat = win32con.DT_NOCLIP | win32con.DT_VCENTER | win32con.DT_EXPANDTABS
    if message == win32con.WM_PAINT:
        hDC, paintStruct = win32gui.BeginPaint(hWnd)
        fontSize = 20

        lf = win32gui.LOGFONT()
        lf.lfFaceName = "Times New Roman"
        lf.lfHeight = fontSize
        lf.lfWeight = 300

        lf.lfQuality = win32con.NONANTIALIASED_QUALITY
        hf = win32gui.CreateFontIndirect(lf)
        win32gui.SelectObject(hDC, hf)

        if len(userAndMessage) > 4:
            win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
            rect = win32gui.GetClientRect(hWnd)
            drawRect = win32gui.DrawText(hDC,userAndMessage[0][0],-1, rect, 
win32con.DT_CALCRECT); 
            win32gui.DrawText(hDC, userAndMessage[0][0], -1, rect, textFormat)

            win32gui.SetTextColor(hDC,win32api.RGB(240,240,240))
            drawrect = win32gui.DrawText(hDC, userAndMessage[0][1], -1, rect, 
win32con.DT_CALCRECT);
            rect = (drawRect[1][0] + drawRect[1][2], drawRect[1][1], drawRect[1][2], 
drawRect[1][3])
            win32gui.DrawText(hDC, userAndMessage[0][1], -1, rect, textFormat)


#####################################################################################
            win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
            rect = (0, drawRect[1][1] + drawRect[1][3], drawRect[1][2], drawRect[1] 
[3])
            drawRect = win32gui.DrawText(hDC,userAndMessage[1][0],-1, rect, 
win32con.DT_CALCRECT); 
            win32gui.DrawText(hDC, userAndMessage[1][0], -1, rect, textFormat)

            win32gui.SetTextColor(hDC,win32api.RGB(240,240,240))
            drawrect = win32gui.DrawText(hDC, userAndMessage[1][1], -1, rect, 
win32con.DT_CALCRECT);
            rect = (drawRect[1][0] + drawRect[1][2], drawRect[1][1], drawRect[1][2], 
drawRect[1][3])
            win32gui.DrawText(hDC, userAndMessage[1][1], -1, rect, textFormat)


#####################################################################################
            win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
            rect = (0, drawRect[1][1] + (drawRect[1][3] // 2), drawRect[1][2], 
drawRect[1][3])
            drawRect = win32gui.DrawText(hDC,userAndMessage[2][0],-1, rect, 
win32con.DT_CALCRECT); 
            win32gui.DrawText(hDC, userAndMessage[2][0], -1, rect, textFormat)

            win32gui.SetTextColor(hDC,win32api.RGB(240,240,240))
            drawrect = win32gui.DrawText(hDC, userAndMessage[2][1], -1, rect, 
win32con.DT_CALCRECT);
            rect = (drawRect[1][0] + drawRect[1][2], drawRect[1][1], drawRect[1][2], 
drawRect[1][3])
            win32gui.DrawText(hDC, userAndMessage[2][1], -1, rect, textFormat)

        #####################################################################################
            win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
            rect = (0, drawRect[1][1] + (drawRect[1][3] // 3), drawRect[1][2], 
drawRect[1][3])
            drawRect = win32gui.DrawText(hDC,userAndMessage[3][0],-1, rect, 
win32con.DT_CALCRECT); 
            win32gui.DrawText(hDC, userAndMessage[3][0], -1, rect, textFormat)

            win32gui.SetTextColor(hDC,win32api.RGB(240,240,240))
            drawrect = win32gui.DrawText(hDC, userAndMessage[3][1], -1, rect, 
win32con.DT_CALCRECT);
            rect = (drawRect[1][0] + drawRect[1][2], drawRect[1][1], drawRect[1][2], 
drawRect[1][3])
            win32gui.DrawText(hDC, userAndMessage[3][1], -1, rect, textFormat)


#####################################################################################
            win32gui.SetTextColor(hDC,win32api.RGB(255,0,0))
            rect = (0, drawRect[1][1] + (drawRect[1][3] // 4), drawRect[1][2], 
drawRect[1][3])
            drawRect = win32gui.DrawText(hDC,userAndMessage[4][0],-1, rect, 
win32con.DT_CALCRECT); 
            win32gui.DrawText(hDC, userAndMessage[4][0], -1, rect, textFormat)

            win32gui.SetTextColor(hDC,win32api.RGB(240,240,240))
            drawrect = win32gui.DrawText(hDC, userAndMessage[4][1], -1, rect, 
win32con.DT_CALCRECT);
            rect = (drawRect[1][0] + drawRect[1][2], drawRect[1][1], drawRect[1][2], 
drawRect[1][3])
            win32gui.DrawText(hDC, userAndMessage[4][1], -1, rect, textFormat)

            win32gui.EndPaint(hWnd, paintStruct)
            return 0

    elif message == win32con.WM_DESTROY:
        print('Being destroyed')
        win32gui.PostQuitMessage(0)
        return 0

    else:
        return win32gui.DefWindowProc(hWnd, message, wParam, lParam)

if __name__ == '__main__':
    main()

再次感谢乌龟