Skip to content

Instantly share code, notes, and snippets.

@hoishing
Last active November 26, 2022 13:22
Show Gist options
  • Save hoishing/a1512e0fc93c234add60f41467ce25a0 to your computer and use it in GitHub Desktop.
Save hoishing/a1512e0fc93c234add60f41467ce25a0 to your computer and use it in GitHub Desktop.
Menu Bar Apps
//strong reference to retain the status bar item object
var statusItem: NSStatusItem?
func applicationDidFinishLaunching(_ aNotification: Notification) {
statusItem = NSStatusBar.system().statusItem(withLength: -1)
guard let button = statusItem?.button else {
print("status bar item failed. Try removing some menu bar item.")
NSApp.terminate(nil)
return
}
button.image = NSImage(named: "MenuBarButton")
button.target = self
button.action = #selector(displayMenu)
}
@IBOutlet weak var appMenu: NSMenu!
@objc func displayMenu() {
guard let button = statusItem?.button else { return }
let x = button.frame.origin.x
let y = button.frame.origin.y - 5
let location = button.superview!.convert(NSMakePoint(x, y), to: nil)
let w = button.window!
let event = NSEvent.mouseEvent(with: .leftMouseUp,
location: location,
modifierFlags: NSEvent.ModifierFlags(rawValue: 0),
timestamp: 0,
windowNumber: w.windowNumber,
context: w.graphicsContext,
eventNumber: 0,
clickCount: 1,
pressure: 0)!
NSMenu.popUpContextMenu(appMenu, with: event, for: button)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment