Skip to content

Instantly share code, notes, and snippets.

@six519
Last active November 6, 2018 10:14
Show Gist options
  • Save six519/ee095ef544286c1145dc69e91aece455 to your computer and use it in GitHub Desktop.
Save six519/ee095ef544286c1145dc69e91aece455 to your computer and use it in GitHub Desktop.
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment