Go で GUI を表示する(RegisterClassEx/CreateWindowEx/GetMessage)
前回の上記の記事に RegisterHotkey を付け足すだけで、Go でグローバルホットキーに対応できる。
後の人のために残しておく。
main.go
package main
import (
"syscall"
"unsafe"
"github.com/blono/win" // Fork of lxn/win see https://qiita.com/manymanyuni/items/c41f5bf0fd141e299336
)
func NewUTF16(s string) *uint16 {
result, _ := syscall.UTF16PtrFromString(s)
return result
}
const (
idMyHotkey = iota
}
func onMessage(window win.HWND, msg uint32, wParam uintptr, lParam uintptr) uintptr {
switch msg {
case case win.WM_HOTKEY:
switch int(wParam) {
case idMyHotkey:
// Hotkey Pressed!!
}
case win.WM_CREATE
win.RegisterHotKey(window, idMyHotkeyCommand, win.MOD_CONTROL|win.MOD_SHIFT, win.VK_SPACE)
case win.WM_CLOSE:
win.UnregisterHotKey(window, idMyHotkey)
win.DestroyWindow(window)
case win.WM_DESTROY:
win.PostQuitMessage(0)
default:
return win.DefWindowProc(window, msg, wParam, lParam)
}
return 0
}
func main() {
windowClass := win.WNDCLASSEX{
LpfnWndProc: syscall.NewCallback(onMessage),
HInstance: win.HINSTANCE(0),
LpszClassName: winut.NewUTF16("test"),
}
windowClass.CbSize = uint32(unsafe.Sizeof(windowClass))
win.RegisterClassEx(&windowClass)
window := win.CreateWindowEx(0, winut.NewUTF16("test"), winut.NewUTF16("test-window"),
win.WS_OVERLAPPEDWINDOW | win.WS_VISIBLE, 100, 100, 500, 500, win.HWND(0), win.HMENU(0), win.HINSTANCE(0), nil)
win.ShowWindow(window, win.SWP_SHOWWINDOW)
win.UpdateWindow(window)
var msg win.MSG
for win.GetMessage(&msg, 0, 0, 0) > 0 {
win.TranslateMessage(&msg)
win.DispatchMessage(&msg)
}
}