Skip to content

Instantly share code, notes, and snippets.

@EliCDavis
Created September 25, 2020 14:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save EliCDavis/aa8c8ee39eb542f5e33166d0f1cb53a9 to your computer and use it in GitHub Desktop.
So it seems programs launched by your golang application are only put in the foreground if your golang application itself is in the foreground. So before launching your application, just put your golang application in the foreground first. Here's what I've done to make a program get launched in the foreground, even though the parent program is i…
package main
import (
"fmt"
"log"
"os"
"os/exec"
"syscall"
"time"
"unsafe"
)
var (
kernel32 = syscall.MustLoadDLL("Kernel32.dll")
getConsoleWindow = kernel32.MustFindProc("GetConsoleWindow")
user32 = syscall.MustLoadDLL("user32.dll")
setForegroundWindow = user32.MustFindProc("SetForegroundWindow")
)
func getWindowPointer() (syscall.Handle, error) {
r, _, err := syscall.Syscall(getConsoleWindow.Addr(), 0, 0, 0, 0)
return syscall.Handle(r), err
}
func bringWindowToForeground(hwnd syscall.Handle) (int, error) {
sucess, _, err := syscall.Syscall(setForegroundWindow.Addr(), 1, uintptr(hwnd), 0, 0)
return int(sucess), err
}
func main() {
winPnt, err := getWindowPointer()
if err != nil {
log.Println("errpr", err)
}
fmt.Printf("this windows pointer: %d;\n", int(winPnt))
// Allows me time to manually click over to another window for sake of example.
time.Sleep(time.Second * 5)
success, err := bringWindowToForeground(winPnt)
if err != nil {
log.Printf("error bringing to foreground: %+v\n", err)
}
fmt.Printf("success: %d;\n", int(success))
output, err := exec.Command("my program").Output()
if err == nil {
os.Stdout.Write(output)
} else {
log.Panicln(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment