检测NSStatusItem (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")
}

我的函数没有被调用,我找不到原因。谢谢你的帮助!

你试过了吗:

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 == NSEvent.EventType.rightMouseUp {
        // Right button click
    } else {
        // Left button click
    }
}

感谢@dbrownjave注意到Swift 4从NSEventType.rightMouseUpNSEvent.EventType.rightMouseUp的变化。

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

更新:迅速4

我已经更新了(Craig Francis)答案

func doSomeAction(sender: NSStatusItem) {
    let event = NSApp.currentEvent!
    if event.type == NSEvent.EventType.rightMouseUp{
        // Right button click
    } else {
        // Left button click
    }

相关内容

  • 没有找到相关文章

最新更新