Toggle capslock

Is it possible to set the capslock key state using AppleScriptObjC or any shell script?

You can build this project with Xcode.

And you can call this “setleds” command via AppleScript’s do shell script command.

スクリーンショット 2023-04-13 23.20.27

Hi Takaaki, thank you for responding.

The note on the Github page says:

Setting the LED on or off does not affect the behavior of that key…

If I understand well, if the capslock is on, the shell will shut down the led but the key will remain on.
That’s the opposite of what I want.

tell application “System Events” to keystroke 57

This code does not have effect to CAPS Lock LED and input text become CAPS.
I could not return input state.
Try this.

Key code 57 does not do anything.
It’s a known issue.

Thanks anyway.

Hmm…My Apple Magic Keyboard (JIS Key) respond this code.
It is strange…

Interesting. Here it’s producing nothing.
I’m using a French version of Monterey.
But I’m not the only one whose facing this issue:

My environment is macOS 13.4beta2 Japanese language environment.

Does the combination of OS Version + language + keyboard type make some difference about CAPS keycode?

I don’t have another language keyboard. So, I have nothing to do with this issue.

See if this still works:

It works for me. Although I’m not sure what this CAPS locking feature is useful for.

This script is the one I was using for a couple of months.
But I noticed that it randomly fails to get the capslock state.

After some diving in the code, I think I’ve isolate the issue:
This script has the same problem than:

use framework "Foundation"
(current application's NSEvent's modifierFlags())

If you run the above script using any shortcut (⌘R in SD), the result will reflect the actual state the the capslock key. (1114112 when capslock is on, 1048576 otherwise)
But if you run it without any other modifier key (for example: by clicking on the ‘run’ button of SE or SD, or by choosing a menu item in FastScripts) the result will always be 0.

That said, what I’m looking for is simply disabling caps lock if it’s enabled.
It can be done like this:

set theScript to "ObjC.import(\"IOKit\");
ObjC.import(\"CoreServices\");

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

    $.IOServiceOpen(
        $.IOServiceGetMatchingService(
            $.kIOMasterPortDefault,
            $.IOServiceMatching(
                $.kIOHIDSystemClass
            )
        ),
        $.mach_task_self_,
        $.kIOHIDParamConnectType,
        ioConnect
    );
    $.IOHIDSetModifierLockState(ioConnect, $.kIOHIDCapsLockState, 0);
    $.IOServiceClose(ioConnect);
	
})();"

run script theScript in "Javascript"

Thank you guys, especially to @CJK

1 Like