2

I need to detect all the keys that the user presses. Using -keyDown: I can get most key presses (alphanumeric, function keys, arrows, space bar, escape, return), but I cannot get any modifier key when it's pressed alone.

How do I detect absolutely any keystroke, including modifier keys?

2 Answers 2

4

Try it:

[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask|NSFlagsChangedMask handler:^NSEvent *(NSEvent *incomingEvent) { if (incomingEvent.type == NSFlagsChanged && (incomingEvent.modifierFlags & NSDeviceIndependentModifierFlagsMask)) { NSLog(@"modifier key down"); } else if (incomingEvent.type == NSKeyDown) { NSLog(@"other key down"); } return incomingEvent; }]; 
Sign up to request clarification or add additional context in comments.

Comments

3

The flagsChanged: method can be useful for detecting the pressing of modifier keys without any other key being pressed simultaneously. For example, if the user presses the Option key by itself, your responder object can detect this in its implementation of flagsChanged:.

2 Comments

Interesting, but I receive two events, on key down and key up. Is there any way to tell which one is it?
You save a copy of the modifierFlags from the previous notification, and compare it to the current modifierFlags to tell you whether the modifier key was just added to the flags, or just removed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.