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

1

8

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.

Iatric answered 17/1, 2021 at 20:35 Comment(0)
W
6

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.

Walley answered 15/4, 2021 at 5:46 Comment(1)
the 200 microseconds delay actually is beetween key down and key up event: hammerspoon.org/docs/hs.eventtap.html#keyStrokeFagaly

© 2022 - 2024 — McMap. All rights reserved.