64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
|
package hot_key
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
winapi "github.com/lxn/win"
|
||
|
"syscall"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ModAlt = 1 << iota
|
||
|
ModCtrl
|
||
|
ModShift
|
||
|
ModWin
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
user32 = syscall.NewLazyDLL("user32")
|
||
|
registerHotKey = user32.NewProc("RegisterHotKey")
|
||
|
unregisterHotKey = user32.NewProc("UnregisterHotKey")
|
||
|
)
|
||
|
|
||
|
var keyHandle = map[int32]func(){0: func() {}}
|
||
|
|
||
|
func RegisterHotKey(Modifiers, KeyCode int, callback func()) (int, error) {
|
||
|
uid := len(keyHandle)
|
||
|
r1, _, err := registerHotKey.Call(0, uintptr(uid), uintptr(Modifiers), uintptr(KeyCode))
|
||
|
if r1 == 1 {
|
||
|
keyHandle[int32(uid)] = callback
|
||
|
return uid, nil
|
||
|
} else {
|
||
|
return 0, err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func UnregisterHotKey(uid int32) error {
|
||
|
r1, _, err := unregisterHotKey.Call(0, uintptr(uid))
|
||
|
if r1 == 1 {
|
||
|
return nil
|
||
|
} else {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func UnregisterAllHotKey() {
|
||
|
for id, _ := range keyHandle {
|
||
|
_ = UnregisterHotKey(id)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ListenHotKey() {
|
||
|
go func() {
|
||
|
msg := &winapi.MSG{}
|
||
|
fmt.Println("Start HotKey Listen...")
|
||
|
for {
|
||
|
winapi.GetMessage(msg, 0, 0, 0)
|
||
|
if msg.Message == winapi.WM_HOTKEY {
|
||
|
if fnc, ok := keyHandle[int32(msg.WParam)]; ok {
|
||
|
fnc()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}()
|
||
|
}
|