Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global keyboard shortcuts for a Mac tray app

Tags:

macos

swift

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).

screenshot

So what I need is for my app to respond to system-wide keyboard shortcuts.

I've tried:

  • HotKey but it doesn't seem to be compatible with Swift 4, or perhaps I can't use Swift Package Manager
  • this answer but again Swift 4 raises several errors that I couldn't solve

Has anyone done it?

like image 540
foucdeg Avatar asked Dec 11 '17 19:12

foucdeg


People also ask

How do I create a shortcut for an app on a Mac?

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.

What is the keyboard shortcut for global search?

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.

How do I find all app Shortcuts on Mac?

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.


2 Answers

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.

like image 182
Sindre Sorhus Avatar answered Oct 07 '22 17:10

Sindre Sorhus


So I ended up getting it to work with HotKey:

  • by using Carthage as a package manager instead of SPM
  • and by not using HotKey's example code from their README, which for some reason didn't work for me, but the one in their example app.

It works great!

like image 24
foucdeg Avatar answered Oct 07 '22 18:10

foucdeg