Swift Snippets
Revision as of 09:21, 11 December 2022 by PeterHarding (talk | contribs) (Created page with " * https://stackoverflow.com/questions/59635971/show-nsmenu-only-on-nsstatusbarbutton-right-click <pre> 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", ac...")
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 }