Call the action when NSStatusBarButton is right clicked

I'm looking for a detection method whenever I NSStatusBarButtoncan right-click (using Swift) and trigger an action.

I am currently setting it up this way:

let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
    if let button = statusItem.button {
        button.image = NSImage(named: "myImage")
        button.alternateImage = NSImage(named: "myImage")
        button.action = Selector("myAction")
    }
}

I was thinking about using button.rightMouseDown(<#theEvent: NSEvent#>)(because there is no "alternateAction"), but, unfortunately, I couldn’t come up with something because I was just starting to program Mac applications.

Update:

, NSView, , ( , , "" ). , , statusBar , , .

+4
2

mouseDown, Mac OS X 10.10 (Yosemite) : NSGestureRecognizer :

func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
    if let button = statusItem.button {
        button.image = NSImage(named: "myImage")
        button.alternateImage = NSImage(named: "myImage")
        button.action = Selector("myAction")

        // Add right click functionality
        let gesture = NSClickGestureRecognizer()
        gesture.buttonMask = 0x2 // right mouse
        gesture.target = self
        gesture.action = "myRightClickAction:"
        button.addGestureRecognizer(gesture)
    }
}

func myRightClickAction(sender: NSGestureRecognizer) {
    if let button = sender.view as? NSButton {
        // Handle your right click event here
    }
}
+2

, : buttonMask 0x2, buttonMask 0x1. NSButton ( NSStatusBarButtons) NSClickGestureRecognizer s, , , , . , , , NSStatusItem view NSView, OS X v10.10 view , " .

, NSView NSStatusItem. NSView -rightMouseUp:, mouse up, , , .

:

#import <Cocoa/Cocoa.h>

@interface TTRightClickDetector : NSView

@property (copy) void (^onRightMouseClicked)(NSEvent *);

@end

#import "TTRightClickDetector.h"

:

@implementation TTRightClickDetector

- (void)rightMouseUp:(NSEvent *)theEvent
{
    if(self.onRightMouseClicked)
    {
        self.onRightMouseClicked(theEvent);
    }
}

@end

:

self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
NSStatusBarButton *button = self.statusItem.button;
button.image = [NSImage imageNamed:@"image"];
button.action = @selector(leftMouseClicked:);

TTRightClickDetector *rightClickDetector = [[TTRightClickDetector alloc] initWithFrame:button.frame];
rightClickDetector.onRightMouseClicked = ^(NSEvent *event){
    [self rightMouseClicked];
};
[button addSubview:rightClickDetector];
+1

All Articles