github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zlog/color_win.go (about) 1 //go:build windows 2 // +build windows 3 4 package zlog 5 6 import ( 7 "syscall" 8 ) 9 10 var ( 11 winEnable bool 12 procSetConsoleMode *syscall.LazyProc 13 ) 14 15 func init() { 16 if supportColor || isMsystem { 17 return 18 } 19 kernel32 := syscall.NewLazyDLL("kernel32.dll") 20 procSetConsoleMode = kernel32.NewProc("SetConsoleMode") 21 22 winEnable = tryApplyOnCONOUT() 23 if !winEnable { 24 winEnable = tryApplyStdout() 25 } 26 } 27 28 func tryApplyOnCONOUT() bool { 29 outHandle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0) 30 if err != nil { 31 return false 32 } 33 34 err = EnableTerminalProcessing(outHandle, true) 35 if err != nil { 36 return false 37 } 38 39 return true 40 } 41 42 func tryApplyStdout() bool { 43 err := EnableTerminalProcessing(syscall.Stdout, true) 44 if err != nil { 45 return false 46 } 47 48 return true 49 } 50 51 func EnableTerminalProcessing(stream syscall.Handle, enable bool) error { 52 var mode uint32 53 err := syscall.GetConsoleMode(stream, &mode) 54 if err != nil { 55 return err 56 } 57 58 if enable { 59 mode |= 0x4 60 } else { 61 mode &^= 0x4 62 } 63 64 ret, _, err := procSetConsoleMode.Call(uintptr(stream), uintptr(mode)) 65 if ret == 0 { 66 return err 67 } 68 69 return nil 70 } 71 72 // IsSupportColor IsSupportColor 73 func IsSupportColor() bool { 74 return supportColor || winEnable 75 }