Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

macos - Left vs Right Click Status Bar Item Mac Swift 2

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...