When I use `NSMenuItem.setShortcut(for) method ` I cannot trigger shortcut keys

#223 · closed · 2 comments

View on GitHub ↗

King-Eternal

<img width="2275" height="1241" alt="Image" src="https://github.com/user-attachments/assets/bf99ee02-36d6-403d-a5d4-a6879d8dade3" /> Here is a demo to demonstrate. [MacOSDemo.zip](https://github.com/user-attachments/files/21783040/MacOSDemo.zip)

Comments

cweider

The primary problem here is that, in the code screenshot, I see nothing connecting the shortcuts to `onCopy` or `onModify`. Note: I’ve not explored MacOSDemo.zip – secure viewing is too much a bother for an initial investigation. For `KeyboardShortcuts` to invoke `onCopy`, a handler must be registered with `onKeyUp(for:)` or `onKeyDown(for:)`: ``` KeyboardShortcuts.onKeyDown(for: Self.hotName) { self.onCopy() } ``` For `NSMenuItem` to invoke the specified selector, `onCopy`, there must be both an `action` and a `target`: ``` let copyItem = NSMenuItem(title: "Copy", action: #selector(onCopy), keyEquivalent: "") item.target = self ```

sindresorhus

This is expected behavior. When you create a `Name` with a default shortcut, it registers as a global hotkey with Carbon, which intercepts the keyboard event before the menu system receives it. `setShortcut(for:)` only sets the *visual display* of the shortcut on the menu item - it doesn't handle the action. You need to use `onKeyDown(for:)` or `events(for:)` to actually respond to the shortcut: ```swift KeyboardShortcuts.onKeyDown(for: .hotName) { [weak self] in self?.onCopy() } ``` If you just want a plain menu shortcut (not a global hotkey), don't use this library - just set `keyEquivalent` directly on the NSMenuItem.