Left vs Right Click Status Bar Item Mac Swift 2

落花浮王杯 提交于 2019-11-27 17:50:29

问题


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 displays a menu with an About and Quit item.

I have been looking but all I could find was command or control click suggestions however I would prefer not to go this route.

Thanks in advance and any help appreciated!


回答1:


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/




回答2:


for this you can use statusItem button property.

    let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)  
    let statusButton = statusItem!.button!
    statusButton?.target = self // or wherever you implement the action method
    statusButton?.action = "statusItemClicked:" // give any name you want
    statusButton?.sendActionOn(Int((NSEventMask.LeftMouseUpMask | NSEventMask.RightMouseUpMask).rawValue)) // what type of action to observe

then you implement the action function, in the above code I named it "statusItemClicked"

func statusItemClicked(sender: NSStatusBarButton!){
    var event:NSEvent! = NSApp.currentEvent!
    if (event.type == NSEventType.RightMouseUp) {
        statusItem?.menu = myMenu //set the menu
        statusItem?.popUpStatusItemMenu(myMenu)// show the menu 
    }
    else{
        // call your function here
    }
}


来源:https://stackoverflow.com/questions/33257848/left-vs-right-click-status-bar-item-mac-swift-2

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