Technical Q&A QA1519

Detecting the Caps Lock Key

Q:  How do I detect when the caps lock key is turned on or off in my Cocoa application?

A: You must implement flagsChanged: in order to detect this key.

NSResponder keyDown: and keyUp: methods do not fire when just a modifier key is pressed. So if you want to catch this event, you will need to override:

- (void)flagsChanged:(NSEvent*) and examine the NSEvent from there.

The flagsChanged: method comes from NSResponder, so any responder in the responder chain can react to it.

Listing 1  Detecting the caps lock key.

- (void)flagsChanged:(NSEvent*)event
{
    if ([event keyCode] == 0x39) // 57 = key code for caps lock
    {
        NSUInteger flags = [event modifierFlags];
        if (flags & NSAlphaShiftKeyMask)
            NSLog(@"capsLock on");
        else
            NSLog(@"capsLock off");
    }
}

Related Documentation



Document Revision History


DateNotes
2013-01-28

Repaired outdated links to documentation.

2007-05-11

New document that explains how to detect when the caps lock key is turned on and off.