My Daily Gist | Ferdinand Silva


Windows API Implementation In Go Sample Code (Change Console Text Color)

 
package main
import (
"fmt"
"syscall"
"unsafe"
)
const (
FOREGROUND_BLACK uint16 = 0x0000
FOREGROUND_BLUE uint16 = 0x0001
FOREGROUND_GREEN uint16 = 0x0002
FOREGROUND_CYAN uint16 = 0x0003
FOREGROUND_RED uint16 = 0x0004
FOREGROUND_PURPLE uint16 = 0x0005
FOREGROUND_YELLOW uint16 = 0x0006
FOREGROUND_WHITE uint16 = 0x0007
)
type (
SHORT int16
WORD uint16
SMALL_RECT struct {
Left SHORT
Top SHORT
Right SHORT
Bottom SHORT
}
COORD struct {
X SHORT
Y SHORT
}
CONSOLE_SCREEN_BUFFER_INFO struct {
Size COORD
CursorPosition COORD
Attributes WORD
Window SMALL_RECT
MaximumWindowSize COORD
}
)
func main() {
var consoleInfo CONSOLE_SCREEN_BUFFER_INFO
kernel32 := syscall.NewLazyDLL("kernel32.dll")
getConsoleScreenBufferInfoProc := kernel32.NewProc("GetConsoleScreenBufferInfo")
setConsoleTextAttributeProc := kernel32.NewProc("SetConsoleTextAttribute")
handle, _ := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
_, _, _ = getConsoleScreenBufferInfoProc.Call(uintptr(handle), uintptr(unsafe.Pointer(&consoleInfo)), 0)
fmt.Println("Original Color")
//set to yellow
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(FOREGROUND_YELLOW), 0)
fmt.Println("Yellow Color")
//set to red
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(FOREGROUND_RED), 0)
fmt.Println("Red Color")
//set to original
_, _, _ = setConsoleTextAttributeProc.Call(uintptr(handle), uintptr(consoleInfo.Attributes), 0)
}
view raw test.go hosted with ❤ by GitHub