7

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

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

4

1 回答 1

6

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

下面是一个方法示例,当从应用程序委托的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]];
}
于 2019-07-18T20:23:53.663 回答