Files
Reims-Go/internal/host/foreground_windows.go
T

108 lines
2.8 KiB
Go

//go:build windows
package host
import (
"sync"
"syscall"
"unsafe"
)
var (
procEnumWindows = user32.NewProc("EnumWindows")
procIsWindowVisible = user32.NewProc("IsWindowVisible")
procIsIconic = user32.NewProc("IsIconic")
procShowWindow = user32.NewProc("ShowWindow")
procSetForegroundWin = user32.NewProc("SetForegroundWindow")
procBringWindowToTop = user32.NewProc("BringWindowToTop")
procAttachThreadInput = user32.NewProc("AttachThreadInput")
)
const swRestore = 9
// ForegroundPID returns the process that owns the foreground window, or 0
// when there is none (locked screen, desktop focused).
func ForegroundPID() uint32 {
hwnd, _, _ := procGetForegroundWindow.Call()
if hwnd == 0 {
return 0
}
var pid uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
return pid
}
var (
focusEnumMu sync.Mutex
focusEnumOnce sync.Once
focusEnumCB uintptr
focusEnumTargetPID uint32
focusEnumFound uintptr
)
func enumFocusWindowProc(hwnd uintptr, _ uintptr) uintptr {
vis, _, _ := procIsWindowVisible.Call(hwnd)
if vis == 0 {
return 1
}
var winPID uint32
_, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&winPID)))
if winPID == focusEnumTargetPID {
focusEnumFound = hwnd
return 0
}
return 1
}
// FocusProcessWindow finds the primary visible top-level window belonging to
// pid, restores it if minimized, and brings it to the foreground.
func FocusProcessWindow(pid uint32) bool {
if pid == 0 {
return false
}
focusEnumOnce.Do(func() {
focusEnumCB = syscall.NewCallback(enumFocusWindowProc)
})
focusEnumMu.Lock()
focusEnumTargetPID = pid
focusEnumFound = 0
_, _, _ = procEnumWindows.Call(focusEnumCB, 0)
found := focusEnumFound
focusEnumMu.Unlock()
if found == 0 {
return false
}
iconic, _, _ := procIsIconic.Call(found)
if iconic != 0 {
_, _, _ = procShowWindow.Call(found, swRestore)
}
fgHwnd, _, _ := procGetForegroundWindow.Call()
curTid, _, _ := procGetCurrentThreadId.Call()
var fgTid uintptr
if fgHwnd != 0 {
fgTid, _, _ = procGetWindowThreadProcessId.Call(fgHwnd, 0)
}
targetTid, _, _ := procGetWindowThreadProcessId.Call(found, 0)
attachedFg := false
attachedTarget := false
if fgTid != 0 && fgTid != curTid {
if r, _, _ := procAttachThreadInput.Call(curTid, fgTid, 1); r != 0 {
attachedFg = true
}
}
if targetTid != 0 && targetTid != curTid && targetTid != fgTid {
if r, _, _ := procAttachThreadInput.Call(curTid, targetTid, 1); r != 0 {
attachedTarget = true
}
}
_, _, _ = procBringWindowToTop.Call(found)
_, _, _ = procSetForegroundWin.Call(found)
if attachedTarget {
_, _, _ = procAttachThreadInput.Call(curTid, targetTid, 0)
}
if attachedFg {
_, _, _ = procAttachThreadInput.Call(curTid, fgTid, 0)
}
return true
}