Skip to content

Program implies that Windows terminal supports ANSI but it's not always true #4

@flexits

Description

@flexits

Although the actual Windows versions support ANSI terminal, it's never guaranteed this support is enabled by default. And if it's not, the program output looks like this:

Image

The solution is to set the flag ENABLE_VIRTUAL_TERMINAL_PROCESSING before calling any clime functions. An implementation example:

const (
	ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
	STD_OUTPUT_HANDLE                  = 0xFFFF_FFFF - 10
)

func EnableAnsi() error {
	modKernel32 := windows.NewLazyDLL("kernel32.dll")
	procGetStdHandle := modKernel32.NewProc("GetStdHandle")
	procGetConsoleMode := modKernel32.NewProc("GetConsoleMode")
	procSetConsoleMode := modKernel32.NewProc("SetConsoleMode")

	h, _, err := procGetStdHandle.Call(uintptr(STD_OUTPUT_HANDLE))
	if h == 0 {
		// TODO it'd be appropriate to use windows.GetLastError()
		return err
	}

	var mode uint32
	r, _, err := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode)))
	if r == 0 {
		return err
	}

	newMode := mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING
	r, _, err = procSetConsoleMode.Call(h, uintptr(newMode))
	if r == 0 {
		return err
	}

	return nil
}

I skimmed through the code but it seems to use mostly stateless function and there's no general initialization function to put the EnableAnsi() call in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions