NSEvent addGlobalMonitorForEventsMatchingMask: Hot

2019-04-13 03:21发布

问题:

I wanna intercept hotkeys that begin with Control+Shift and ends with a character (mandatory).
I have the following code:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSFlagsChangedMask handler: ^(NSEvent *event) {
    NSUInteger flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
    if(flags == NSControlKeyMask + NSShiftKeyMask){
        NSLog(@"pressed!");
    }
}];

What do i need to add to my code to check if the user pressed ControlShift+character, and what character the user pressed?
The code NSLog(@"pressed!"); will be executed only if what i said above is true.

This is my pseudo-code for what i'm looking for:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSFlagsChangedMask handler: ^(NSEvent *event) {
    NSUInteger flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
    if((flags == NSControlKeyMask + NSShiftKeyMask) && [event containsCharacter]){
       NSLog(@"%@", [event character];
    }
}];

So if the user presses Control+Shift+1 i'll do one thing, if Control+Shift+2 other thing, and so on...

回答1:

You need to compare bitwise:

- (void)keyDown:(NSEvent *)theEvent { 
    if ([theEvent modifierFlags] & (NSControlKeyMask | NSShiftKeyMask)) { 
        if (theEvent.keyCode == 1/* add the right key code */) {
            NSLog(@"Do something");
        }
    } else { 
        [super keyDown:theEvent]; 
    } 
} 


回答2:

Try this:

 [NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) {
    NSUInteger key = 8; // 8 is "C"
    NSUInteger modifier = NSControlKeyMask + NSShiftKeyMask; 
    if ([event keyCode] == key && [NSEvent modifierFlags] == modifier)

NSLog(@"pressed!");

}];