问题
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