/
w32hotkeys.go
79 lines (67 loc) · 1.32 KB
/
w32hotkeys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package w32hotkey
// #define WIN32_LEAN_AND_MEAN
// #define NOCRYPT
// #define NOGDI
// #define NOSERVICE
// #define NOMCX
// #define NOIME
// #include <windows.h>
import "C"
import (
"runtime"
)
const (
ALT uint = 0x0001
CONTROL uint = 0x0002
SHIFT uint = 0x0004
WIN uint = 0x0008
NOREPEAT uint = 0x4000
)
type Hotkey struct {
ModKey C.UINT
Vk C.UINT
Callback Callback
}
type Hotkeys struct {
hotkeys map[C.int]*Hotkey
id C.int
}
type Callback func(id int)
func New() *Hotkeys {
hotkeys := new(Hotkeys)
hotkeys.hotkeys = make(map[C.int]*Hotkey)
hotkeys.id = 0
return hotkeys
}
func (this *Hotkeys) AddHotkey(ModKey, Vk uint, callback Callback) int {
hotkey := new(Hotkey)
hotkey.ModKey = C.UINT(ModKey)
hotkey.Vk = C.UINT(Vk)
hotkey.Callback = callback
this.hotkeys[this.id] = hotkey
oldId := this.id
this.id++
return int(oldId)
}
func (this *Hotkeys) Start() {
go this.run()
}
func (this *Hotkeys) run() {
runtime.LockOSThread()
for id, hk := range this.hotkeys {
if C.RegisterHotKey(nil, id, hk.ModKey, hk.Vk) == 0 {
panic("could not register hotkey")
}
}
for {
var msg C.MSG
C.GetMessage((*C.struct_tagMSG)(&msg), nil, 0, 0)
if msg.message == C.WM_HOTKEY {
id := C.int(msg.wParam)
hk, ok := this.hotkeys[id]
if ok {
go hk.Callback(int(id))
}
}
}
}