问题
My Cocoa application supports dropping files onto its Dock icon, but I'd like different behavior depending on whether a modifier key is held down (Command, Option, etc.).
I tried checking the modifierFlags
for the currentEvent
, but they are the same regardless of whether a modifier is held down, or not (I was testing with the Option key).
Code:
// Code is inside my AppDelegate
- (void)application:(NSApplication *)theApplication openFiles:(NSArray *)files {
BOOL optDown = (([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
== NSAlternateKeyMask);
NSLog(@"flags: %u, down? %@", [[NSApp currentEvent] modifierFlags],
optDown ? @"YES" : @"NO");
}
Output (dropping a file with the Option key down, then not):
flags: 1088, down? NO
flags: 1088, down? NO
Expected
flags: <not sure>, down? YES
flags: <different>, down? NO
回答1:
In general, you can't expect [NSApp currentEvent]
to have anything to do with the current user state if your app is not frontmost.
To get the hardware state, which will work regardless of the frontmost app, GetCurrentKeyModifiers()
is supported back to 10.0 (including 64-bit); [NSEvent modifierFlags]
is another option if you can require 10.6.
来源:https://stackoverflow.com/questions/5994656/how-to-tell-if-a-modifier-key-is-down-during-drop-on-dock