Toggle caps lock programmatically using applescript

Solution 1:

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.

Solution 2:

Though not exactly the same thing, a similar action might be to simulate the shift key being held down. You can command System Events to keep the shift key down until you command it to be reset:

tell application "System Events" to key down shift

To reset:

tell application "System Events" to key up shift

It has obvious differences to activating caps lock, which are worth a footnote.


WARNING: It can be humorous then quickly annoying to execute the first command and lose the ability to, for example, input any digit (which can only be done if the shift key is up). The action of the shift key will affect mouse clicks, shortcuts, and so on. To illustrate, if you typically run a script by pressing R, this will not be possible while the shift key is active, as the system will register R (thankfully, +⟨click⟩ on menu items appears to perform the same action as a simple click).