NSEvent addGlobalMonitorForEventsMatchingMask: Hotkey Intercepting

心不动则不痛 提交于 2019-12-21 22:32:34

问题


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!");

}];


来源:https://stackoverflow.com/questions/12379961/nsevent-addglobalmonitorforeventsmatchingmask-hotkey-intercepting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!