如何用Hammerspoon绑定Cmd+Shift组合键实现类Windows输入法切换?
解决Hammerspoon绑定Cmd+Shift切换输入法的问题
问题原因
你之前的两种写法都不符合Hammerspoon的API规则:
- 第一种写法中,
hs.hotkey.bind的第二个参数为空字符串,该API要求必须传入具体的普通按键(而非仅修饰键组合),所以无法触发。 - 第二种写法把Shift当作普通按键传入,但Shift属于修饰键,不能作为
bind方法的key参数使用,因此绑定无效。
另外,单纯的修饰键组合(Cmd+Shift)无法通过hs.hotkey.bind实现绑定,因为该API仅支持修饰键+普通按键的组合,需要用hs.eventtap来监听按键状态实现。
正确实现代码
-- 替换成你自己的输入法ID,可通过在Hammerspoon控制台执行hs.keycodes.sourceIDs()获取 local chineseInputID = "com.apple.inputmethod.SCIM.ITABC" local englishInputID = "com.apple.keylayout.US" -- 创建按键事件监听 local shiftCmdListener = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event) local modifiers = event:getFlags() -- 检测是否仅按下Cmd+Shift组合键 if modifiers.cmd and modifiers.shift and not modifiers.alt and not modifiers.ctrl then local currentInput = hs.keycodes.currentSourceID() -- 切换输入法 if currentInput == chineseInputID then hs.keycodes.currentSourceID(englishInputID) else hs.keycodes.currentSourceID(chineseInputID) end -- 阻止事件传递,避免触发系统默认快捷键 return true end return false end) -- 启动监听 shiftCmdListener:start()
使用步骤
- 打开Hammerspoon控制台(点击菜单栏图标→Console),执行
hs.keycodes.sourceIDs(),找到你常用的输入法ID,替换代码中的chineseInputID和englishInputID。 - 将代码放入Hammerspoon的配置文件(
~/.hammerspoon/init.lua),重启Hammerspoon即可生效。
内容的提问来源于stack exchange,提问作者AlonMln
相关产品推荐
相关产品推荐

