r/applescript • u/41br05 • Jul 16 '24
Send keystrokes in isolation - ignoring any other keys pressed or held simultaneously
if frontApp is "Microsoft Word" then
tell application "Microsoft Word"
tell application "System Events" to keystroke "s" using {command down}
end tell
end if
How to send CMD+S ignoring any other pressed or held keys?
For example, if I hold shift while writing something in Word, it will result in SHIFT+CMD+S, opening a window prompting you to save the doc into a new file.
I am writing an auto-save script for Office 365 Word because idiots at Microsoft force you to save your files on OneDrive if you want to use the auto-save feature.
3
Upvotes
4
u/AmplifiedText Jul 16 '24 edited Jul 16 '24
This doesn't seem possible with AppleScript, but it is possible.
Save this as "emit-save-hotkey.m" or whatever, compile the code then call with AppleScript:
do shell script "/path/to/emit-save-hotkey"The magic is the
kCGEventSourceStatePrivate, which makes sure all events this program emits aren't affected by the state of the keyboard or any other simulated states (like if you hold Shift on the on-screen keyboard, etc).EDIT: I only tested on macOS 10.14 Mojave, but I'm confident it will work with more modern versions of macOS as long as you get the permissions correct System Settings > Privacy > Accessibility. macOS should prompt you to grant these permissions when you run this program for the first time.
2
u/sargonian Jul 16 '24
That seems rather roundabout... why can't you just do: