0

I'm building a NSStatusBar app and want to call different functions depending on if the user clicked left- or right on the icon.

Here is what I have so far:

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

func applicationDidFinishLaunching(aNotification: NSNotification) {
    let icon = NSImage(named: "statusIcon")
    icon?.setTemplate(true)

    statusItem.image = icon
    statusItem.menu = statusMenu
}

With this it shows up the statusMenu by every click. How can I distinguish the mouseEvents?

ixany
  • 5,433
  • 9
  • 41
  • 65
  • 1
    https://stackoverflow.com/questions/38999700/detect-left-and-right-click-events-on-nsstatusitem-swift – BB9z Jan 03 '19 at 13:14
  • Possible duplicate of [Detect left and right click events on NSStatusItem (Swift)](https://stackoverflow.com/questions/38999700/detect-left-and-right-click-events-on-nsstatusitem-swift) – ixany Jan 03 '19 at 16:15

1 Answers1

0

This snippet

func menuSelected (sender:AnyObject) {
  var clickMask: Int = 0
  if let clickEvent = NSApp.currentEvent! {  // see what caused calling of the menu action
    // modifierFlags contains a number with bits set for various modifier keys
    // ControlKeyMask is the enum for the Ctrl key
    // use logical and with the raw values to find if the bit is set in modifierFlags
    clickMask = Int(clickEvent.modifierFlags.rawValue) & Int(NSEventModifierFlags.ControlKeyMask.rawValue)
  }
  if clickMask != 0 { ... } // click with Ctrl pressed
}

from my code checks for a ctrl-click. It's place in the method that is called from a menu item like this:

let item = NSMenuItem(title: title, action: Selector("menuSelected:"), keyEquivalent: "")
qwerty_so
  • 35,448
  • 8
  • 62
  • 86
  • See NSEvent.pressedMouseButtons – qwerty_so Jan 05 '15 at 15:30
  • Could you please add some comments to your code? Unfortunately I don't understand what's happening there. I'm not sure where to place it as well, since i haven't an IBAction. – ixany Jan 05 '15 at 17:11
  • I had a look into NSEvent too but had no luck getting left/right out of that. Will try a bit more. I used Ctrl-click to get different click variants for the status bar. – qwerty_so Jan 05 '15 at 17:53
  • Dear Kilian, is there a Swift 3 solution for this? – ixany Aug 27 '16 at 09:24
  • My last try with Swift3 did hurt. I'm too old to work as early adopter and will be waiting for Swift4 to get mature before switching to Swift3. Go ahead and let that XCode make the transformation for you. Save your work before you do that :-/ – qwerty_so Aug 27 '16 at 09:53