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.
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.
flagsChanged: method comes from
NSResponder, so any responder in the responder chain can react to it.
Listing 1 Detecting the caps lock key.
if ([event keyCode] == 0x39) // 57 = key code for caps lock
NSUInteger flags = [event modifierFlags];
if (flags & NSAlphaShiftKeyMask)
Document Revision History
Repaired outdated links to documentation.
New document that explains how to detect when the caps lock key is turned on and off.