How to support right click menu to NSStatusItem

Issue #707

The trick is to set the button oinside of statusItem to send actions on both leftMouseUp and rightMouseUp.

Another thing to note is we use popUpMenu on NSStatusItem, although it is marked as deprecated on macOS 10.14. We can set menu but that overrides left click.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import Omnia

private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
private let statusItemMenuHandler = MenuHandler()

func setupStatusMenu() {
if let button = statusItem.button {
button.image = NSImage(named: NSImage.Name("statusMenuIcon"))
button.contentTintColor = NSColor.black
button.action = #selector(statusMenuButtonTouched(_:))
button.sendAction(on: [.leftMouseUp, .rightMouseUp]) // This is important

statusItemMenuHandler.add(title: "About", action: {
NSWorkspace.shared.open(URL(string: "https://onmyway133.com/pushhero")!)
})
}
}

@objc
private func statusMenuButtonTouched(_ sender: NSStatusBarButton) {
guard let event = NSApp.currentEvent else { return }
switch event.type {
case .rightMouseUp:
statusItem.popUpMenu(statusItemMenuHandler.menu)
// statusItem.menu = statusItemMenuHandler.menu // this overrides left click
default:
popover.toggle()
}
}

Updated at 2020-12-08 05:11:24

Comments