MacOS – How to activate Mouse Keys with an apple script or the command line

applescriptcatalinamacosmouse-keysterminal

I have set up mouse keys to activate when clicking option five times.

Unfortunately, it appears that I cannot activate mouse keys with this script

repeat 5 times
    tell application "System Events" to key code 58
end repeat

I also tried defaults write com.apple.universalaccess mouseDriver 1

I have system preferences blocked, so I can't turn on mouse keys by going into system preferences.

How can I activate mouse keys using a terminal command or script?

Best Answer

I was also not able to automate enabling "Mouse Keys" by key stroking the "Option" key 5 times. However, I was able to figure out a workaround using this... keystroke "z" using {command down, option down, control down}. On OS Catalina, as you can see in the following image, using this keyboard shortcut will open the Accessibility Options overlay window. And once this window is open, you can set Mouse Keys to On or Off.

enter image description here

Here is the Accessibility Options overlay window which opens when using that keyboard shortcut.

enter image description here

Here is the AppleScript code I created which automates the process of enabling Mouse Keys.

tell application "System Events" to tell application process "UniversalAccessControl"
    keystroke "z" using {command down, option down, control down}
    delay 3
    click checkbox "Enable Mouse Keys" of window "Accessibility Options"
    delay 1
    click button "Done" of window "Accessibility Options"
end tell

I saved my version of the code as a .scpt file and added it to the Script menu in the menu bar for testing purposes. Using Automator, you can easily create a new "Quick Action" and add the AppleScript code, save the file then in System Preferences, you can create a keyboard shortcut for the file.

The following GIF demonstrates the process.

enter image description here

————————

If the entire process I just mentioned does not work for you, this following code may do the trick.

tell application "System Events"
    keystroke "z" using {command down, option down, control down}
    delay 3
    repeat 4 times
        key code 48 -- Tab Key
        delay 1.5
    end repeat
    key code 49 -- Space Key
    delay 1
    key code 36 -- Return Key
end tell