简体   繁体   中英

Swift: Right/Left click on NSStatusBar

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?

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: "")

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