Skip to content

Instantly share code, notes, and snippets.

@obonyojimmy
Created January 1, 2017 02:50
Show Gist options
  • Select an option

  • Save obonyojimmy/d6b263212a011ac7682ac738b7fb4c70 to your computer and use it in GitHub Desktop.

Select an option

Save obonyojimmy/d6b263212a011ac7682ac738b7fb4c70 to your computer and use it in GitHub Desktop.

Revisions

  1. obonyojimmy created this gist Jan 1, 2017.
    55 changes: 55 additions & 0 deletions active-window.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    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)
    }
    }
    }