检测NSStatusItem(Swift)上的左右键单击事件

ixa*_*any 1 nsevent nsstatusitem nsstatusbar swift

我正在构建状态栏应用程序,并希望根据用户是向左还是向右单击来调用不同的操作.这是我到目前为止所拥有的:

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")
}
Run Code Online (Sandbox Code Playgroud)

我的功能没有被调用,我找不到我们的原因.我感谢任何帮助!

Cra*_*cis 7

你有没有尝试过:

button.sendAction(on: [.leftMouseUp, .rightMouseUp])
Run Code Online (Sandbox Code Playgroud)

然后看看doSomeAction()功能中按下了哪个鼠标按钮?

所以它看起来像......

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
    }

}
Run Code Online (Sandbox Code Playgroud)

https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift