繁体   English   中英

macOS:有没有办法知道用户何时尝试通过Dock图标退出应用程序?

[英]macOS: Is there any way to know when the user has tried to quit an application via its Dock icon?

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

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

实际上,应用程序可以通过检查当前是否正在处理当前的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]];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM