Left vs Right Click Status Bar Item Mac Swift 2

前端 未结 2 2039
孤独总比滥情好
孤独总比滥情好 2020-12-16 14:02

I have been trying to develop a simple program that sits in the Mac\'s status bar. I need it so that if you left click, it runs a function, but if you right click it display

2条回答
  •  时光说笑
    2020-12-16 14:41

    Swift 3

    let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
    
    if let button = statusItem.button {
        button.action = #selector(self.statusBarButtonClicked(sender:))
        button.sendAction(on: [.leftMouseUp, .rightMouseUp])
    }
    
    func statusBarButtonClicked(sender: NSStatusBarButton) {
        let event = NSApp.currentEvent!
    
        if event.type == NSEventType.rightMouseUp {
            print("Right click")
        } else {
            print("Left click")
        }
    }
    

    Swift 4

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
    if let button = statusItem.button {
        button.action = #selector(self.statusBarButtonClicked(_:))
        button.sendAction(on: [.leftMouseUp, .rightMouseUp])
    }
    
    func statusBarButtonClicked(sender: NSStatusBarButton) {
        let event = NSApp.currentEvent!
    
        if event.type == NSEvent.EventType.rightMouseUp {
            print("Right click")
        } else {
            print("Left click")
        }
    }
    

    A longer post is available at https://samoylov.eu/2016/09/14/handling-left-and-right-click-at-nsstatusbar-with-swift-3/

提交回复
热议问题