简体   繁体   中英

Double-click action for menu bar icon in Mac OSX

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!

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM