Swift: Right/Left click on NSStatusBar

ぃ、小莉子 提交于 2020-01-03 05:58:08

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/27781167/swift-right-left-click-on-nsstatusbar

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