我就是想加入一个功能:从 xxx 软件切换到 iTerm ,输入法切换到英文;从 iTerm 回到 xxx 软件,将输入法调回原来的状态。
不会 lua ,代码都是照猫画虎的,但是感觉应该没问题。结果也没问题,可是发生了很多次切换,菜单栏输入法图标会有一阵短暂而急促的抖动,有点逼死强迫症了。
不知道为什么 Hammerspoon 监测不到 Alfred ,然后我发现 Alfred 自己的 Force Keyboard 功能也有这问题。
如图,在 VSCode (不设定)和 iTerm (设定为切换到 ABC 输入法)之间切换时:
所有代码如下:
-- 切换输入法 local function Chinese() hs.keycodes.currentSourceID("im.rime.inputmethod.Squirrel.Rime") end local function English() hs.keycodes.currentSourceID("com.apple.keylayout.ABC") end local appInputMethod = { iTerm2 = English, Alfred = English, ['Sublime Text'] = English, ['EuDic LightPeek'] = English, ['微信'] = Chinese } -- activated 时切换到设定的输入法,deactivated 时恢复输入法 currentID = "" function applicationWatcher(appName, eventType, appObject) if (eventType == hs.application.watcher.activated) then for app, fn in pairs(appInputMethod) do if app == appName then currentID = hs.keycodes.currentSourceID() fn() end end end if eventType == hs.application.watcher.deactivated then for app, fn in pairs(appInputMethod) do if app == appName then hs.keycodes.currentSourceID(currentID) currentID = hs.keycodes.currentSourceID() end end end end appWatcher = hs.application.watcher.new(applicationWatcher):start() -- 输入法切换提示 hs.keycodes.inputSourceChanged(function() if hs.keycodes.currentMethod() == nil then hs.alert.show("ABC", hs.alert.defaultStyle, hs.screen.mainScreen(), 2) else hs.alert.show("拼音", hs.alert.defaultStyle, hs.screen.mainScreen(), 2) end end)