使用NSAppleEventManager捕获所有退出事件

时间:2011-12-23 20:02:07

标签: macos events

当我的Mac OS应用程序退出时,我希望它询问用户“你确定要退出[是] [否]”。

我试过这个:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    // Install a custom quit event handler
    NSAppleEventManager* appleEventManager = [NSAppleEventManager sharedAppleEventManager];
    [appleEventManager setEventHandler:self andSelector:@selector(handleQuitEvent:withReplyEvent:) forEventClass:kCoreEventClass andEventID:kAEQuitApplication];
}

// Handler for the quit apple event
- (void)handleQuitEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent {
    // Insert YES/NO-dialog here
    // if(blahahaha..
    //[NSApp terminate:self];
}

但它只能解决当我在Dock上右键点击我的应用程序然后选择“退出”时的退出。如果我按下Cmd-Q或从应用程序菜单中选择退出,我的处理程序不会被调用...

1 个答案:

答案 0 :(得分:2)

并非所有这些案件都涉及Apple Events。相反,请处理应用委托方法-applicationShouldTerminate: