Printing output to a command window when golang application is compiled with -ldflags -H=windowsgui

后端 未结 5 1826
野性不改
野性不改 2021-02-05 14:09

I have an application that usually runs silent in the background, so I compile it with

go build -ldflags -H=windowsgui 

To check

5条回答
  •  甜味超标
    2021-02-05 14:30

    Answer above was helpful but alas it did not work for me out of the box. After some additional research I came to this code:

    // go build -ldflags -H=windowsgui
    package main
    
    import "fmt"
    import "os"
    import "syscall"
    
    func main() {
        modkernel32 := syscall.NewLazyDLL("kernel32.dll")
        procAllocConsole := modkernel32.NewProc("AllocConsole")
        r0, r1, err0 := syscall.Syscall(procAllocConsole.Addr(), 0, 0, 0, 0)
        if r0 == 0 { // Allocation failed, probably process already has a console
            fmt.Printf("Could not allocate console: %s. Check build flags..", err0)
            os.Exit(1)
        }
        hout, err1 := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
        hin, err2 := syscall.GetStdHandle(syscall.STD_INPUT_HANDLE)
        if err1 != nil || err2 != nil { // nowhere to print the error
            os.Exit(2)
        }
        os.Stdout = os.NewFile(uintptr(hout), "/dev/stdout")
        os.Stdin = os.NewFile(uintptr(hin), "/dev/stdin")
        fmt.Printf("Hello!\nResult of console allocation: ")
        fmt.Printf("r0=%d,r1=%d,err=%s\nFor Goodbye press Enter..", r0, r1, err0)
        var s string
        fmt.Scanln(&s)
        os.Exit(0)
    }
    

    The key point: after allocating/attaching the console, there is need to get stdout handle, open file using this handle and assign it to os.Stdout variable. If you need stdin you have to repeat the same for stdin.

提交回复
热议问题