I want to share this function, hopefully some will find it useful.
My use case is the following: I want a key to be bound to an app:
- if the App is the frontmost app
- key sequence is passed to the app
- otherwise
- bring the app to the front
- "pass through" the key to the app
Here is the code, with an example of how I bind Ctrl-Cmd C to emacs.
bundleKeys = {}
function bound_key_issue(hotKey, key1, key2)
hotKey:disable()
hs.eventtap.keyStroke(key1, key2)
hotKey:enable()
end
function bind_key_to_app(bundleID, key1, key2)
bundleKeys[bundleID] = hs.hotkey.bind(key1, key2, function ()
local hotkey = bundleKeys[bundleID]
if not hotkey then
hs.alert("Bug: bundleID key not found but it has been defined.
Simply generating event" .. bundleID)
hs.eventtap.keyStroke(key1, key2)
return
end
if not switch_by_bundle_id(bundleID) then
hs.alert(bundleID .. " app is not running. Simply generating event")
bound_key_issue(hotkey, key1, key2)
return
end
-- at this point app is running, we are just waiting for it
-- at most 1 second
local count = 0
while count < 10 and not is_front_by_bundle_id(bundleID) do
hs.timer.usleep(100)
count = count + 1
end
if is_front_by_bundle_id(bundleID) then
bound_key_issue(hotkey, key1, key2)
else
hs.alert("EMacs was not able to be front before command")
end
end)
end
bind_key_to_app("org.gnu.Emacs", {"ctrl", "cmd"}, "c")
--
--dmg
---
D M German
http://turingmachine.org