I have the following code: (can be copy-pasted to New macOS project)
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSAppl
I'm using this code on Catalina. Rather than performClick like some of the other answers suggest, I had to manually position the popup. This works for me with external monitors.
func applicationDidFinishLaunching(_ aNotification: Notification) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.action = #selector(onClick)
statusItem.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
menu = NSMenu()
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
menu.delegate = self
}
@objc func onClick(sender: NSStatusItem) {
let event = NSApp.currentEvent!
if event.type == NSEvent.EventType.rightMouseUp {
// right click, show quit menu
statusItem.menu = menu;
menu.popUp(positioning: nil,
at: NSPoint(x: 0, y: statusItem.statusBar!.thickness),
in: statusItem.button)
} else {
// main click
}
}
@objc func menuDidClose(_ menu: NSMenu) {
// remove menu when closed so we can override left click behavior
statusItem.menu = nil
}