# termcolor outputs stuff like '\033[0m'. It doesn't work in Windows 10's cmd.

class Color:
    kernel32 = hStdOut = None
    
    def init():
        import ctypes
        Color.user32 = ctypes.CDLL('user32.dll'); Color.kernel32 = ctypes.CDLL('kernel32.dll')
        # https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute
        # HANDLE WINAPI GetStdHandle(DWORD nStdHandle)
        # BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes)
        # WINCON.H:
        #define FOREGROUND_BLUE      0x0001 // text color contains blue.
        #define FOREGROUND_GREEN     0x0002 // text color contains green.
        #define FOREGROUND_RED       0x0004 // text color contains red.
        #define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
        #define BACKGROUND_BLUE      0x0010 // background color contains blue.
        #define BACKGROUND_GREEN     0x0020 // background color contains green.
        #define BACKGROUND_RED       0x0040 // background color contains red.
        #define BACKGROUND_INTENSITY 0x0080 // background color is intensified.
        STD_OUTPUT_HANDLE = -11
        Color.hStdOut = Color.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    
    def __init__(m, fg_str_or_color, bg = ''):
        if isinstance(fg_str_or_color, int):
            import sys
            sys.stdout.flush()
            Color.kernel32.SetConsoleTextAttribute(Color.hStdOut, fg_str_or_color)
            return
        def f(s):
            t = { 'b':1, 'B':8+1, 'g':2, 'G':8+2, 'r':4, 'R':8+4 }
            d = 0
            for c in s: d |= t.get(c, 0)
            #print(s, hex(d))
            return d
        m.__init__(f(fg_str_or_color) | (f(bg) << 4))

    # 注意缩进和空行!缩进不对__str__成了__init__的内部函数,折腾了半天。    
    def __str__(m): return 'Color'
    
Color.init()

if __name__ == '__main__':
    Color('G'); print('Green ', end=''); Color('rgb'); print('gray')
    print(Color('RGB', 'G'), 'Hello', Color('rgb'), 'world')
    # Color Hello Color world
    # python先把参数求值完再去调print。
    # CMD的color命令也可以设颜色。color/?

# 如果有人想做个cmdcolor包,请把代码拿去自便。甚至可以扩展为WFP - Windows Fun Pack :-)
# 比如一个线程空白DialogBox,另一个干事情。GetWindowDC()后就可以画画了。哪怕GetDC(NULL)
# 在屏幕上画呢。pip install pywin32; D:\Python39\Lib\site-packages\PyWin32.chm
# 简历里一句"开发过一个python wheel,在github上有n颗星"?I admit我爱幻想。
# win32console里一堆函数,如SetConsoleTitle,就是没有SetConsoleTextAttribute。
# 四子棋: https://www.cnblogs.com/funwithwords/p/15626636.html
# 画线和实心椭圆…… GDI
posted on 2021-12-10 07:14  华容道专家  阅读(797)  评论(0)    收藏  举报