Skip to content

Instantly share code, notes, and snippets.

@audrenbdb
Last active July 7, 2021 20:20
Show Gist options
  • Save audrenbdb/c975b0fad398a11360e37d66e3798c4b to your computer and use it in GitHub Desktop.
Save audrenbdb/c975b0fad398a11360e37d66e3798c4b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"os/exec"
"syscall"
"time"
"unsafe"
)
const (
//Activates and displays the window.
//If the window is minimized or maximized,
//the system restores it to its original size and position
swRestore = 9
)
var (
user32 = syscall.MustLoadDLL("user32.dll")
procEnumWindows = user32.MustFindProc("EnumWindows")
procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow")
procShowWindow = user32.MustFindProc("ShowWindow")
procGetWindowThreadProcessId = user32.MustFindProc("GetWindowThreadProcessId")
)
func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func FindWindowByPID(pid int) (syscall.Handle, error) {
var hwnd syscall.Handle
cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr {
var i uintptr
procGetWindowThreadProcessId.Call(uintptr(h), uintptr(unsafe.Pointer(&i)))
if uintptr(pid) == i {
hwnd = h
return 0
}
return 1
})
EnumWindows(cb, 0)
if hwnd == 0 {
return 0, fmt.Errorf("no window with pid found with pid %d", pid)
}
return hwnd, nil
}
func main() {
cmd := exec.Command(`notepad`)
cmd.Start()
pid := cmd.Process.Pid
log.Println(pid)
time.Sleep(5 * time.Second)
h, err := FindWindowByPID(pid)
if err != nil {
log.Fatal(err)
}
procShowWindow.Call(uintptr(h), swRestore)
procSetForegroundWindow.Call(uintptr(h))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment