如何检测macOS应用是否由AppleScript激活?
判断应用是否由AppleScript激活的方法
可以通过检查Apple事件来区分应用是被AppleScript激活还是用户手动启动的——AppleScript的activate命令会触发特定的Apple事件,以下是具体实现方案:
方案1:启动时检查启动选项
在应用首次启动时,通过launchOptions中的NSApplicationLaunchAppleEventKey判断是否由Apple事件触发启动:
import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { func application(_ application: NSApplication, didFinishLaunchingWithOptions launchOptions: [NSApplication.LaunchOptionsKey : Any]? = nil) -> Bool { if let appleEvent = launchOptions?[.appleEvent] as? NSAppleEventDescriptor { let eventClass = appleEvent.eventClass let eventID = appleEvent.eventID // 匹配AppleScript activate命令对应的事件 if eventClass == AEEventClass(kAEMiscStandards), eventID == AEEventID(kAEActivate) { print("activated from AppleScript") } else { print("launched via other Apple event") } } else { print("user clicked or other non-Apple event method") } return true } }
方案2:激活时检查当前Apple事件
如果应用已经在后台运行,被AppleScript激活时会触发applicationDidBecomeActive,此时可以通过NSAppleEventManager获取当前Apple事件判断来源:
import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidBecomeActive(_ notification: Notification) { guard let event = NSAppleEventManager.shared().currentAppleEvent else { print("user activated or non-Apple event trigger") return } let eventClass = event.eventClass let eventID = event.eventID if eventClass == AEEventClass(kAEMiscStandards), eventID == AEEventID(kAEActivate) { print("activated from AppleScript") } } }
关键说明
- AppleScript的
activate命令对应的Apple事件类为kAEMiscStandards,事件ID为kAEActivate,匹配这两个值即可确定激活来源。 - 手动点击图标启动/激活应用时,不会生成对应的Apple事件,因此
currentAppleEvent会为空,或launchOptions中不存在appleEvent键。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

