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
    {
        unsigned flags = [event modifierFlags];
        if (flags & NSAlphaShiftKeyMask)
            NSLog(@"capsLock on");
        else
            NSLog(@"capsLock off");
    }
}

Related Documentation

Back to Top 

Document Revision History

DateNotes
2007-05-11First Version

Posted: 2007-05-11


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.