对于在命令行中彩色输出,Go本身没有提供直接系统层次的API调用封装,不过提供了调用系统API的包Syscall,然后我们使用它调用SetConsoleTextAttribute来进行色彩设置。

func ColorPrintln(s string, i int) {
    kernel32 := syscall.NewLazyDLL("kernel32.dll")
    proc := kernel32.NewProc("SetConsoleTextAttribute")
    handle, _, _ := proc.Call(uintptr(syscall.Stdout), uintptr(i)) //12 Red light
 
    fmt.Println(s)
 
    handle, _, _ = proc.Call(uintptr(syscall.Stdout), uintptr(7)) //White dark
    CloseHandle := kernel32.NewProc("CloseHandle")
    CloseHandle.Call(handle)
}

完整范例

package main

import (
    "fmt"
    "syscall"
)

func ColorPrintln(s string, i int) {
    kernel32 := syscall.NewLazyDLL("kernel32.dll")
    proc := kernel32.NewProc("SetConsoleTextAttribute")
    handle, _, _ := proc.Call(uintptr(syscall.Stdout), uintptr(i)) //12 Red light
 
    fmt.Println(s)
 
    handle, _, _ = proc.Call(uintptr(syscall.Stdout), uintptr(7)) //White dark
    CloseHandle := kernel32.NewProc("CloseHandle")
    CloseHandle.Call(handle)
}

func main() {
    ColorPrintln("我是CRoot",12)
    ColorPrintln("https://xcroot.com",11)
}

 

页面下部广告

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

鲁ICP备17018668号-1