Skip to content

Instantly share code, notes, and snippets.

@thedemoncat
Forked from obonyojimmy/active-window.go
Created February 20, 2021 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedemoncat/d5989bedb5d66b0e40096d94aace2f01 to your computer and use it in GitHub Desktop.
Save thedemoncat/d5989bedb5d66b0e40096d94aace2f01 to your computer and use it in GitHub Desktop.
Go lang get current foreground window
package main
import (
"fmt"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
var (
mod = windows.NewLazyDLL("user32.dll")
procGetWindowText = mod.NewProc("GetWindowTextW")
procGetWindowTextLength = mod.NewProc("GetWindowTextLengthW")
)
type (
HANDLE uintptr
HWND HANDLE
)
func GetWindowTextLength(hwnd HWND) int {
ret, _, _ := procGetWindowTextLength.Call(
uintptr(hwnd))
return int(ret)
}
func GetWindowText(hwnd HWND) string {
textLen := GetWindowTextLength(hwnd) + 1
buf := make([]uint16, textLen)
procGetWindowText.Call(
uintptr(hwnd),
uintptr(unsafe.Pointer(&buf[0])),
uintptr(textLen))
return syscall.UTF16ToString(buf)
}
func getWindow(funcName string) uintptr {
proc := mod.NewProc(funcName)
hwnd, _, _ := proc.Call()
return hwnd
}
func main() {
for {
if hwnd := getWindow("GetForegroundWindow") ; hwnd != 0 {
text := GetWindowText(HWND(hwnd))
fmt.Println("window :", text, "# hwnd:", hwnd)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment