Double-click action for menu bar icon in Mac OSX

三世轮回 提交于 2019-12-11 06:53:18

问题


I'm writing a small Mac OSX app that displays a menu bar icon. When clicked, a menu pops up.

I'd like to have a "default" action for the menu bar icon. Basically, to execute an action when double-clicking it, without having to select the action from the menu.

I looked over the Apple docs and there's is such a thing in NSStatusItem called doubleAction, but it's soft deprecated and does not (seem to) work. More over, the docs it says to use the button property, but trying to do so results in the compiler error shown below:

Any code or guidance are much appreciated, thanks!


回答1:


The situation as it stands today (Xcode 7.3.1, OSX 10.11.4):

  • the doubleAction of NSStatusItem is deprecated (and NOT actually working).
  • Apple tells you to use the button property - but there's no header for doubleAction (I wonder if the implementation exists). Oh, it's also read-only.
  • there are no other options regarding left/right/double click in any of the NSStatusItem's properties.

The workaround: create a category for NSButton (the exact same that Apple was talking about) and implement a custom click handler that posts a notification when a double click was detected, like the following:

@implementation NSButton (CustomClick)

- (void)mouseDown:(NSEvent *)event {
    if (self.tag != kActivateCustomClick) {
        [super mouseDown:event];
        return;
    }

    switch (event.clickCount) {
        case 1: {
            [self performSelector:@selector(callMouseDownSuper:) withObject:event afterDelay:[NSEvent doubleClickInterval]];
            break;
        }
        case 2: {
            [NSRunLoop cancelPreviousPerformRequestsWithTarget:self];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"double_click_event" object:nil];
            break;
        }
    }
}

- (void)callMouseDownSuper:(NSEvent *)event {
    [super mouseDown:event];
}

@end

As you can see, this handler only handles NSButton instances that have a specific tag value.

When a click is detected, I defer the call to super for handling by the system's double-click interval. If within that time I receive another click, I cancel the call to super and treat it as a double-click.

Hope it helps!




回答2:


You can use NSApp.currentEvent

self.statusItem.button.target = self;
self.statusItem.button.action = @selector(clickOnStatusItem:);

...

- (void)clickOnStatusItem:(id)sender {
    if (NSApp.currentEvent.clickCount == 2) {
        // Double click on status item
    }
}

also, you can process a right mouse button on the status bar item



来源:https://stackoverflow.com/questions/39399626/double-click-action-for-menu-bar-icon-in-mac-osx

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