问题
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?
回答1:
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;
}];
回答2:
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:.
来源:https://stackoverflow.com/questions/22887085/detect-any-key-press-including-modifier-keys-on-os-x