NSMenuItem keyEquivalent under Status Menu

Several years ago, I developed a status menu application in Objective-C. And I'm developing a new one in Swift. I have some lines of code in AppDelegate to show a status menu (NSMenu).


And I see Command H in the status menu. If I press Command H, the application won't call showHome()


class AppDelegate: NSObject, NSApplicationDelegate {
    // MARK: - Variables
    var statusItem = NSStatusItem()
   
    // MARK: - IBOutlet
    @IBOutlet weak var statusMenu: NSMenu!
   
    func applicationWillFinishLaunching(_ notification: Notification) {
    makeStatusMenu()
    }
   
    func makeStatusMenu() {
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let img = NSImage(named: "StatusMenuImage") {
            statusItem.image = img.resize(w: 18.0, h: 18.0)
        }
        statusItem.menu = statusMenu
       
        let showHomeMenuItem = NSMenuItem(title: "Show Home", action:#selector(showHome), keyEquivalent: "h")
        statusMenu.addItem(showHomeMenuItem)
    }
   
    @objc func showHome() {
       
    }
}


What am I doing wrong?


Thanks.

If I press Command H, the application won't call showHome()


Your key equivalent is h (lowercap).

        let showHomeMenuItem = NSMenuItem(title: "Show Home", action:#selector(showHome), keyEquivalent: "h")

Is it what you want ?

What happens if you press Command-h ?

Does the menu work correctly when you select it ?


When I test your code, I get errors:

Value of type 'NSImage' has no member 'resize'


What do you connect the IBOutlet to ? Is it a menu you inserted in menuBar ?

What is the structure ?

- NSMenuItem inserted in ManuBar

- with an NSMenu inside ?

Assuming your app is an LSUIElement or, equivalently, its activationPolicy is .accessory, then it's not the frontmost application. Some other application is frontmost and displays its main menu in the menu bar. A standard item in the application menu of normal applications is Hide <App Name>. That item's standard keyboard shortcut is Command-H. That's probably overriding your menu item's keyboard shortcut. After all, Command-H can only be associated with one active menu item at a time.


Try using a different shortcut.

Thanks. But I've removed an existing key equivalent for Command + H (Including Hide app).

If what I have is


let showHomeMenuItem = NSMenuItem(title: "Show Home", action:#selector(showHome), keyEquivalent: "h")


, then what appears on my status menu is Command + H. If what I have is


let showHomeMenuItem = NSMenuItem(title: "Show Home", action:#selector(showHome), keyEquivalent: "H")


, then what appears on my status menu is Command + Shift + H. And I'll get beeped if I press Command + Shift + H.

NSMenuItem keyEquivalent under Status Menu
 
 
Q