Show NSMenu only on NSStatusBarButton right click?

前端 未结 4 1103
一向
一向 2020-12-18 01:23

I have the following code: (can be copy-pasted to New macOS project)

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSAppl         


        
4条回答
  •  情话喂你
    2020-12-18 01:39

    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
        }
    

提交回复
热议问题