Skip to content

Instantly share code, notes, and snippets.

@ZenLiuCN
Created February 5, 2023 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZenLiuCN/eaad6990a295ab8e417b03352427c101 to your computer and use it in GitHub Desktop.
Save ZenLiuCN/eaad6990a295ab8e417b03352427c101 to your computer and use it in GitHub Desktop.
unit for attch to console with windows gui application
//go:build windows
/*
* written by Zen.Liu, License as MIT
*/
package main
import (
"os"
s "syscall"
)
// https://www.tillett.info/2013/05/13/how-to-create-a-windows-program-that-works-as-both-as-a-gui-and-console-application/
const AttachParentProcess = ^uintptr(0)
func allocConsole() {
aOut := attachable(s.STD_OUTPUT_HANDLE)
aIn := attachable(s.STD_INPUT_HANDLE)
aErr := attachable(s.STD_ERROR_HANDLE)
ac := false
kernel32 := s.MustLoadDLL("kernel32.dll")
if aErr && aOut {
if r, _, _ := kernel32.MustFindProc("AttachConsole").Call(AttachParentProcess); r != 0 {
ac = true
} else if r, _, _ = kernel32.MustFindProc("AllocConsole").Call(); r != 0 {
ac = true
}
}
if ac {
if aOut {
os.Stdout, _ = os.OpenFile("CONOUT$", os.O_WRONLY, 0666)
}
if aErr {
os.Stderr, _ = os.OpenFile("CONOUT$", os.O_WRONLY, 0666)
}
if aIn {
os.Stderr, _ = os.OpenFile("CONIN$", os.O_RDONLY, 0666)
}
}
}
func attachable(std int) bool {
if hOut, _ := s.GetStdHandle(std); hOut != 0 {
tOut, _ := s.GetFileType(hOut)
if tOut == s.FILE_TYPE_DISK || tOut == s.FILE_TYPE_PIPE {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment