Application exit event

MobX picture MobX · Nov 20, 2009 · Viewed 8.5k times · Source

I am developing an application in cocoa. My application shows a pop up sheet initially. I need to know which event is fired when we try to exit the application by right clicking and selecting "exit" on the icon in dock, because I can't exit the application because of the popup sheet. How can I solve this?

Answer

Rob Keniger picture Rob Keniger · Nov 20, 2009

Your app is sent a quit Apple Event when the Quit item is selected in the Dock menu. If you want to intercept this you will need to install a custom Apple Event Handler for this event. Note that it's normal for sheets to prevent application termination until the sheet is dismissed, so if you change this behavior your app will work differently to other applications.

Here is a simple example of how to override the default handler for quit Apple Events in your application delegate:

- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
    //install the 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
{
    [self terminate:self];
}