keystrokehammerspoon

Hammerspoon: continuously send keystrokes to one application, while using others normally


Ok, so I have a script with Hammerspoon that executes key stokes for me. Simple example:

hs.hotkey.bind({'cmd','alt','ctrl'}, "b", function() 
    hs.eventtap.keyStroke({}, "Left", 200000)
    hs.eventtap.keyStroke({}, "Left", 200000)
    hs.eventtap.keyStroke({}, "Right", 200000)
    hs.eventtap.keyStroke({}, "Right", 200000)
end)

I know I can filter this script to only work in specific applications, but my question is: is it possible to send these key strokes to one application, while using my physical keyboard normally in another application? Like having the key strokes sent 'in the background', so they aren't registered in the application I'm currently using.


Solution

  • You can query the app, store it in a variable and then use that to send those keystrokes to that application:

    local myApp = hs.application.applicationsForBundleID('com.apple.finder')[1]
    hs.eventtap.keyStroke({"cmd"}, "2", 200000, myApp)
    

    This would send key down events CMD + 2 to the Finder app (more precisely: the first app with this bundle id) immediately, then send the respective key up events 200000 microseconds (200 milliseconds) later.

    I would probably do the setting of the variable outside the keystroke bind function, so that it does not happen on every keystroke but rather at the beginning.