Detect left and right click events on NSStatusItem

2019-06-04 09:27发布

问题:

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
    }