【问题标题】:macOS: Is there any way to know when the user has tried to quit an application via its Dock icon?macOS:有什么方法可以知道用户何时尝试通过其 Dock 图标退出应用程序?
【发布时间】:2019-11-25 14:08:45
【问题描述】:

Cocoa 应用程序有什么方法可以检测用户何时尝试通过其 Dock 菜单退出它,而不是通过其他方法?

通常可以使用应用程序委托的applicationShouldTerminate: 方法捕获和响应退出事件。但是,此方法似乎无法区分来自应用程序主菜单、其 Dock 图标、Apple 事件或任何其他常规退出应用程序方法的退出请求。我很好奇是否有任何方法可以准确地知道用户是如何尝试退出应用程序的。

【问题讨论】:

标签: macos cocoa exit nsapplication nsapplication-delegate


【解决方案1】:

事实上,应用程序可以通过检查当前是否正在处理 AppleEvent 来了解其退出的原因,如果是,则检查它是否是退出事件以及是否是发送的 Dock它。 (请参阅this thread 讨论如何判断应用程序是否因为系统正在注销或关闭而退出。)

下面是一个方法示例,当从应用程序委托的 applicationShouldTerminate: 方法调用时,如果应用程序通过 Dock 退出,该方法将返回 true:

- (bool)isAppQuittingViaDock {
    NSAppleEventDescriptor *appleEvent = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];

    if (!appleEvent) {
        // No Apple event, so the app is not being quit by the Dock.
        return false;
    }

    if ([appleEvent eventClass] != kCoreEventClass || [appleEvent eventID] != kAEQuitApplication) {
        // Not a 'quit' event
        return false;
    }

    NSAppleEventDescriptor *reason = [appleEvent attributeDescriptorForKeyword:kAEQuitReason];  

    if (reason) {
        // If there is a reason for this 'quit' Apple event (such as the current user is logging out)
        // then it didn't occur because the user quit the app through the Dock.
        return false;
    }

    pid_t senderPID = [[appleEvent attributeDescriptorForKeyword:keySenderPIDAttr] int32Value];

    if (senderPID == 0) {
        return false;
    }

    NSRunningApplication *sender = [NSRunningApplication runningApplicationWithProcessIdentifier:senderPID];

    if (!sender) {
        return false;
    }

    return [@"com.apple.dock" isEqualToString:[sender bundleIdentifier]];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多