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?

4

2 回答 2

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:.

于 2014-04-05T21:34:56.950 回答
3

试试看:

[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;
}];
于 2014-04-06T13:21:31.027 回答