小编典典

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

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")
}

没有调用我的函数,也找不到我们的原因。感谢您的帮助!


阅读 390

收藏
2020-07-07

共1个答案

小编典典

你有没有尝试过:

button.sendAction(on: [.leftMouseUp, .rightMouseUp])

然后看到该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
    }

}

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

2020-07-07