MacOS – Toggle caps lock programmatically using applescript

applescriptcaps-lockmacosmojave

I'm looking to toogle capslock programmatically using applescript. Here is something I tried to make it work. It seems to work for all other keys except capslock.

tell application "System Events"
    key code 57
end tell

57 is the key code for caps lock

Best Answer

Submitting a separate answer, as it is entirely distinct from my first in that it solves the issue at hand. Credit goes to @user3439894 who pointed the OP and I to a link (Toggle caps lock programmatically) that features some source code written in C that can programmatically toggle/set the state of the caps lock. Thus credit goes also to the original author of that code, for which I offer a translation into JavaScript for Automation (JXA), which is the JavaScript flavour of AppleScript.

This script toggles the state of caps lock upon each run:

ObjC.import("IOKit");
ObjC.import("CoreServices");


(() => {
    var ioConnect = Ref();
    var state = Ref();

    $.IOServiceOpen(
        $.IOServiceGetMatchingService(
            $.kIOMasterPortDefault,
            $.IOServiceMatching(
                $.kIOHIDSystemClass
            )
        ),
        $.mach_task_self_,
        $.kIOHIDParamConnectType,
        ioConnect
    );
    $.IOHIDGetModifierLockState(ioConnect, $.kIOHIDCapsLockState, state);
    $.IOHIDSetModifierLockState(ioConnect, $.kIOHIDCapsLockState, !state[0]);
    $.IOServiceClose(ioConnect);
})();

This, like any AppleScript, can be run from within Script Editor (choose the language option in the navigation bar at the top of the window). Sadly, Script Debugger doesn't cater for JXA. But, in practice, the script will be most usefully executed by way of some other automation software, such as Automator, Keyboard Maestro, Alfred, etc., all of which can execute JXA scripts directly; and any software that doesn't provide this option can execute it by way of the shell command osascript:

osascript -l JavaScript /path/to/script.jxa.applescript

You can use an .applescript or .scpt file extension to save the script.