I am developing a Mac app using Swift 4 which only runs as an Agent (it only has a menu in the tray). I'm completely new to Swift.
I want it to respond to keyboard shortcuts, but the basic shortcuts (see picture) only work when the app has focus (in my case, when the menu is being clicked).
So what I need is for my app to respond to system-wide keyboard shortcuts.
I've tried:
Has anyone done it?
On your Mac, choose Apple menu > System Preferences, click Keyboard , then click Shortcuts. Select App Shortcuts on the left, click the Add button , click the Application pop-up menu, then choose a specific app or All Applications.
Open the Global Search app by pressing its shortcut (the default is SUPER + / - Windows key + forward slash). Type in the search bar to find apps, Layouts, Workspaces or actions.
Show or move all open windows Show all open windows for the current app: Press Control-Down Arrow. If App Exposé is enabled in Trackpad settings, you can also swipe down with three or four fingers. To return to the desktop, press the keys again or swipe up.
I made a Swift package that makes this very easy:
import KeyboardShortcuts
extension KeyboardShortcuts.Name {
static let startFiveRounds = Self("startFiveRounds", default: .init(.t, modifiers: [.command, .option]))
}
@main
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
KeyboardShortcuts.onKeyUp(for: .startFiveRounds) {
// …
}
}
}
Even though you already solved your problem, I think this could be useful for other people having the same problem.
I would also recommend letting the user pick their own keyboard shortcut instead of hardcoding it. My package comes with a control where the user can set their preferred shortcut.
So I ended up getting it to work with HotKey:
It works great!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With