LoginSignup
10
8

More than 5 years have passed since last update.

GoでWin32APIのコールバックを使う方法

Posted at

syscall.NewCallbackを使えばいいようです。
以下は、コールバックを使用するEnumChildWindowsを利用して、5秒後にForegroundウィンドウの子ウィンドウを表示するサンプルです。

child_windows.go
package main

import (
    "fmt"
    "syscall"
    "time"

    "github.com/AllenDang/w32"
)

var mod = syscall.NewLazyDLL("user32.dll")

func getWindow(funcName string) uintptr {
    proc := mod.NewProc(funcName)
    hwnd, _, _ := proc.Call()
    return hwnd
}

func printChildWindows(hwnd uintptr) {
    proc := mod.NewProc("EnumChildWindows")
    f := func(hwnd uintptr, lparam uintptr) int {
        text := w32.GetWindowText(w32.HWND(hwnd))
        fmt.Println("child:", text, "# hwnd:", hwnd)
        return 1
    }
    proc.Call(hwnd, syscall.NewCallback(f), 0)
}

func main() {
    time.Sleep(5 * time.Second)
    hwnd := getWindow("GetForegroundWindow")
    text := w32.GetWindowText(w32.HWND(hwnd))
    fmt.Println("parent:", text, "# hwnd:", hwnd)
    printChildWindows(hwnd)
}

なお、上記でも使用しているWin32 APIラッパーとして以下がありますが、すべてを網羅しているわけではないようです。
https://github.com/AllenDang/w32

他にも
https://github.com/lxn/win
がありますが、定義されてる関数がやや少なめ?

これらとhttps://godoc.org/golang.org/x/sys/windows を見て必要なAPIなかったら自力でWin32APIを呼ぶ必要がありそうです。

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8