From 804c4b0c124bda83a0e0b771810bb85600d244b5 Mon Sep 17 00:00:00 2001 From: Kevin F Date: Sat, 24 Dec 2022 15:50:09 -0600 Subject: [PATCH] Initial commit --- examples/example.go | 13 ++++++++ getwindow/getwindow.go | 14 +++++++++ getwindow/getwindow_windows.go | 54 ++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 examples/example.go create mode 100644 getwindow/getwindow.go create mode 100644 getwindow/getwindow_windows.go diff --git a/examples/example.go b/examples/example.go new file mode 100644 index 0000000..782f8cd --- /dev/null +++ b/examples/example.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + + "github.com/egosown/getwindow" +) + +func main() { + + fmt.Println(getwindow.GetWindow()) + +} diff --git a/getwindow/getwindow.go b/getwindow/getwindow.go new file mode 100644 index 0000000..773a7af --- /dev/null +++ b/getwindow/getwindow.go @@ -0,0 +1,14 @@ +//go:build linux +// +build linux + +package getwindow + +import "os/exec" + +func GetWindow() (string, error) { + win, err := exec.Command("xdotool getactivewindow getwindowname").Output() + if err != nil { + return "", err + } + return string(win), nil +} diff --git a/getwindow/getwindow_windows.go b/getwindow/getwindow_windows.go new file mode 100644 index 0000000..ece9d2a --- /dev/null +++ b/getwindow/getwindow_windows.go @@ -0,0 +1,54 @@ +//go:build windows +// +build windows + +package getwindow + +import ( + "errors" + "golang.org/x/sys/windows" + "syscall" + "unsafe" +) + +var ( + mod = windows.NewLazyDLL("user32.dll") + procGetClassNameW = mod.NewProc("GetClassNameW") +) + +type ( + HANDLE uintptr + HWND HANDLE +) + +func getClassName(hwnd HWND) (name string, err error) { + n := make([]uint16, 256) + p := &n[0] + r0, _, e1 := syscall.Syscall(procGetClassNameW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(p)), uintptr(len(n))) + if r0 == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + return + } + name = syscall.UTF16ToString(n) + return +} + +func getWindow(funcName string) uintptr { + proc := mod.NewProc(funcName) + hwnd, _, _ := proc.Call() + return hwnd +} + +func GetWindow() (string, error) { + + hwnd := getWindow("GetForegroundWindow") + if hwnd != 0 { + cn, _ := getClassName(HWND(hwnd)) + return cn, nil + } + return "", errors.New("Could not get window") + +}