10.5: Use Caps Lock to send keystrokes via AppleScript

Feb 12, '08 07:30:00AM

Contributed by: mark hunte

I finally had that eureka moment, on how to detect Caps Lock using Applescript, while trying to help out on this forum thread about auto-logging out from a Mac.

The Applescript calls KeyboardViewerServer.app, and checks the value of the CAPS key via the Keyboard Viewer window. A return value of 1 means the Caps Lock key is down, and a return of 0 means it's up. The really strange -- but good -- thing is that even if the Keyboard Viewer window is not actually visible, the value still gets returned. (If it pops up the first time you run the script, just close its window). Here's a test script to demonstrate how it works:

on idle
  tell application "System Events"
    tell application "KeyboardViewerServer" to activate
    set CAPS to (get value of checkbox "⇪" of window 1 of application process "KeyboardViewerServer") as number
    if CAPS is 1 then
      tell application "TextEdit" to activate
      repeat until CAPS is 0
        set CAPS to (get value of checkbox "⇪" of window 1 of application process "KeyboardViewerServer") as number
        keystroke "1"
      end repeat
    end if
    return 1
  end tell
end idle
Save the code as an application with the Stay Open box checked, then run it. TextEdit should launch, and when you press Caps Lock, the digit 1 will start appearing on your screen. Press it again, and the numbers will stop. This one is used to send the keystroke "1" to World of Warcraft as long as Caps Lock is down. Obviously, you can send whatever keystroke you want by modifying the script.

[robg adds: This worked for me when I tested it.]

Comments (10)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080202094656148