问题
I’m building a status bar app and want to call different actions depending on if the user clicked left or right. Here’s what I have so far:
var statusItem = NSStatusBar.system().statusItem(withLength: -1)
statusItem.action = #selector(AppDelegate.doSomeAction(sender:))
let leftClick = NSEventMask.leftMouseDown
let rightClick = NSEventMask.rightMouseDown
statusItem.button?.sendAction(on: leftClick)
statusItem.button?.sendAction(on: rightClick)
func doSomeAction(sender: NSStatusItem) {
print("hello world")
}
My function is not called and I couldn’t find our why. I appreciate any help!
回答1:
Have you tried:
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
Then seeing which mouse button was pressed in the doSomeAction()
function?
So it will look something like...
let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = statusItem.button {
button.action = #selector(self.doSomeAction(sender:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
}
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEventType.rightMouseUp {
// Right button click
} else {
// Left button click
}
}
https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift
回答2:
Updated: SWIFT 4
I've updated (Craig Francis) answer
func doSomeAction(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp{
// Right button click
} else {
// Left button click
}
来源:https://stackoverflow.com/questions/38999700/detect-left-and-right-click-events-on-nsstatusitem-swift