Detect left and right click events on NSStatusItem (Swift)

回眸只為那壹抹淺笑 提交于 2019-12-08 08:10:45

问题


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

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