package trigger import ( "context" "fmt" "runtime" "strings" "sync" "syscall" "time" "unsafe" ) const ( wmHotkey = 0x0312 wmQuit = 0x0012 modAlt = 0x0001 modControl = 0x0002 modShift = 0x0004 modWin = 0x0008 hotkeyMsgBuf = 16 ) func init() { Register("hotkey", func(params map[string]any) (Trigger, error) { hotkey, _ := params["hotkey"].(string) if hotkey == "" { return nil, fmt.Errorf("hotkey: missing param \"hotkey\" (e.g. \"ctrl+alt+d\")") } mods, vk, err := parseHotkey(hotkey) if err != nil { return nil, err } return &hotkeyTrigger{mods: mods, vk: vk, hotkey: hotkey}, nil }) } // parseHotkey 解析 "ctrl+alt+d" 形式的热键描述。 func parseHotkey(s string) (mods uint32, vk uint16, err error) { for _, p := range strings.Split(strings.ToLower(s), "+") { switch p { case "ctrl": mods |= modControl case "alt": mods |= modAlt case "shift": mods |= modShift case "win": mods |= modWin case "": return 0, 0, fmt.Errorf("hotkey: empty modifier in %q", s) default: if vk != 0 { return 0, 0, fmt.Errorf("hotkey: multiple keys in %q", s) } vk = charVK(p) if vk == 0 { return 0, 0, fmt.Errorf("hotkey: unsupported key %q", p) } } } if vk == 0 { return 0, 0, fmt.Errorf("hotkey: missing key in %q", s) } return mods, vk, nil } // charVK 将单个字符映射为虚拟键码(字母/数字)。 func charVK(c string) uint16 { if len(c) != 1 { return 0 } ch := c[0] switch { case ch >= 'a' && ch <= 'z': return uint16(ch - 'a' + 'A') // VK 不区分大小写 case ch >= '0' && ch <= '9': return uint16(ch) } return 0 } // hotkeyTrigger 注册全局热键并监听 WM_HOTKEY。 type hotkeyTrigger struct { mods uint32 vk uint16 hotkey string // 原始配置字符串(事件 payload 回传,供规则匹配) mu sync.Mutex started bool emit func(Event) cancel context.CancelFunc done chan struct{} threadID uint32 } func (t *hotkeyTrigger) ID() string { return "hotkey" } func (t *hotkeyTrigger) Name() string { return "全局快捷键" } func (t *hotkeyTrigger) Start(ctx context.Context, emit func(Event)) error { t.mu.Lock() defer t.mu.Unlock() if t.started { return nil } ctx, cancel := context.WithCancel(ctx) t.cancel = cancel t.emit = emit t.done = make(chan struct{}) t.started = true go t.loop(ctx) return nil } func (t *hotkeyTrigger) Stop() error { t.mu.Lock() defer t.mu.Unlock() if !t.started { return nil } t.started = false t.cancel() if t.threadID != 0 { // 唤醒消息循环,否则 GetMessage 可能永久阻塞。 _ = postThreadMessage(t.threadID, wmQuit, 0, 0) } <-t.done return nil } func (t *hotkeyTrigger) loop(ctx context.Context) { // 与鼠标钩子同理:RegisterHotKey / GetMessage / Stop 的 WM_QUIT // 必须固定在同一 OS 线程。 runtime.LockOSThread() defer runtime.UnlockOSThread() defer close(t.done) t.threadID = getCurrentThreadId() const id = 1 r, _, _ := procRegisterHotKey.Call(0, id, uintptr(t.mods), uintptr(t.vk)) if r == 0 { // 注册失败(热键被占用等):静默返回,Stop 幂等。 return } defer procUnregisterHotKey.Call(0, id) for { var msg winMsg n, err := getMessage(&msg, 0, 0, 0) if n == 0 || n == -1 || err != nil { return } select { case <-ctx.Done(): return default: } if msg.message == wmHotkey { t.emit(Event{ Type: t.ID(), Timestamp: time.Now(), Payload: map[string]any{"hotkey": t.hotkey}, }) } } } // --- Win32 胶水(hotkey 专用,保持 DLL 访问集中于本包) --- var ( procRegisterHotKey = syscall.NewLazyDLL("user32.dll").NewProc("RegisterHotKey") procUnregisterHotKey = syscall.NewLazyDLL("user32.dll").NewProc("UnregisterHotKey") procGetMessageW = syscall.NewLazyDLL("user32.dll").NewProc("GetMessageW") procPostThreadMessageW = syscall.NewLazyDLL("user32.dll").NewProc("PostThreadMessageW") procGetCurrentThreadId = syscall.NewLazyDLL("kernel32.dll").NewProc("GetCurrentThreadId") ) func getCurrentThreadId() uint32 { r, _, _ := procGetCurrentThreadId.Call() return uint32(r) } func postThreadMessage(threadID uint32, msg uint32, wParam, lParam uintptr) error { r, _, err := procPostThreadMessageW.Call(uintptr(threadID), uintptr(msg), wParam, lParam) if r == 0 { return err } return nil } type winMsg struct { hwnd uintptr message uint32 wParam uintptr lParam uintptr time uint32 pt struct{ x, y int32 } } func getMessage(msg *winMsg, hwnd uintptr, min, max uint32) (int32, error) { r, _, err := procGetMessageW.Call( uintptr(unsafe.Pointer(msg)), hwnd, uintptr(min), uintptr(max)) return int32(int64(r)), err }