I'm developing a Mac application for the menu bar to manage a list of values copied via command + c. I would like my app to perform actions when I press that key combination, even when it is not active. I tried using the addGlobalMonitorForEvents method but it never gets triggered.
//
// iMemoStackApp.swift
// iMemoStack
//
// Created by Cristiano Aloigi on 30/11/23.
//
import SwiftUI
@main
struct iMemoStackApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
MenuBarExtra("iMemoStack", systemImage: "list.bullet.clipboard") {
ContentView()
}
.menuBarExtraStyle(.window)
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
var keyMonitor: Any?
func applicationDidFinishLaunching(_ notification: Notification) {
print("start")
let accessEnabled = AXIsProcessTrustedWithOptions(
[kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
print(accessEnabled)
startMonitoringKeys()
}
func startMonitoringKeys() {
keyMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { (event: NSEvent) in
if event.modifierFlags.contains(.command)
&& event.characters == "c" {
print("comando copia eseguito")
}
if event.modifierFlags.contains(.command)
&& event.characters == "v" {
print("comando incolla eseguito")
}
}
}
func stopMonitoringKeys() {
if let keyMonitor = keyMonitor {
NSEvent.removeMonitor(keyMonitor)
self.keyMonitor = nil
}
}
func applicationWillTerminate(_ notification: Notification) {
stopMonitoringKeys()
}
}