How do I handle keyboard shortcuts and focus on macOS using Swift?

Handling keyboard shortcuts and managing focus in macOS applications using Swift can enhance user experience by providing quicker access to functionalities. Below is an example of how to create a macOS application that responds to keyboard shortcuts and manages focus on views effectively.

import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.closable, .titled, .resizable], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.title = "Keyboard Shortcuts Example" window.makeKeyAndOrderFront(nil) let menu = NSMenu() let appMenuItem = NSMenuItem() menu.addItem(appMenuItem) NSApp.mainMenu = menu let appMenu = NSMenu(title: "Application") appMenu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApp.terminate(_:)), keyEquivalent: "q")) appMenuItem.submenu = appMenu // Register global keyboard shortcut let eventMask: NSEvent.EventTypeMask = [.keyDown] NSEvent.addGlobalMonitorForEvents(matching: eventMask) { (event) in if event.modifierFlags.contains(.command) && event.keyCode == 15 { // 'R' key print("Command-R pressed") // You can add your functionality here. } } } }

swift macOS keyboard shortcuts focus management Cocoa framework