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

后端 未结 5 1778
野性不改
野性不改 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条回答
  •  猫巷女王i
    2021-02-05 14:41

    You can get the desired behavior without using -H=windowsgui; you'd basically create a standard app (with its own console window), and hide it until the program exits.

    func Console(show bool) {
        var getWin = syscall.NewLazyDLL("kernel32.dll").NewProc("GetConsoleWindow")
        var showWin = syscall.NewLazyDLL("user32.dll").NewProc("ShowWindow")
        hwnd, _, _ := getWin.Call()
        if hwnd == 0 {
                return
        }
        if show {
           var SW_RESTORE uintptr = 9
           showWin.Call(hwnd, SW_RESTORE)
        } else {
           var SW_HIDE uintptr = 0
           showWin.Call(hwnd, SW_HIDE)
        }
    }
    

    And then use it like this:

    func main() {
        Console(false)
        defer Console(true)
        ...
        fmt.Println("Hello World")
        ...
    }
    

提交回复
热议问题