Custom view NSMenuItem not responding to keyEquivalent

I set custom NSViewin NSMenuItemfor my own drawing and rendering. However, the "keyEquivalent" assigned NSMenuItemdoes not seem to respond. I understand that processing drawings and actions requires self-processing, but I seem to be unable to capture the key request, no matter what I do. I tried a subclass of NSApplication sendEvent, but this does not work, since my application is NSStatusBarItem(LSUIElement), and events from NSEventTrackingRunLoopMode(when the menu is unavailable) do not reach NSApplication sendEvent.

Then I tried to use:

- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action

This does not work, since it is never called, even if I assigned a delegate to the main menu to the controller.

Does anyone know how to capture keyEquivalent events in NSMenuItems when using a custom view?

Thank!

+3
source share
1 answer

I know this is an old post, and you probably passed it a long time ago, but I had the same problem, and I repeatedly met with your message when trying to find a solution, so I decided to share what worked for me.

NSApplication sendEvent. , , , , NSMenu NSStatusBarItem. - int, , NSMenuItem.

-(void)sendEvent:(NSEvent *)theEvent
{
    if([theEvent type] == NSKeyUp){
        NSInteger mod = ([theEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask);

        if(mod == NSCommandKeyMask) {
            NSInteger keyEquiv = [[theEvent characters] isEqualToString:@"0"]
            ? 10
            : [[theEvent characters] integerValue];
            if(keyEquiv > 0) {
                NSMenuItem *item = [[(MyAppDelegate *)[self delegate] myStatusMenu] itemAtIndex:(keyEquiv - 1)];
                if([[item keyEquivalent] integerValue] == keyEquiv){
                    [[item target] performSelector:[item action] withObject:item];
                }
            }
        }
    }
    [super sendEvent:theEvent];
}
+1

Source: https://habr.com/ru/post/1790583/


All Articles