Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Cmd-Q in Cocoa Application (and Menu Item 'Quit Application' programmatically)

I have created a gaming application that has only one window. Application is created without a help of .xib files as described here: How can I create a GUI and react to Cocoa events programmatically?

Now, I can catch standard 'key up/down' events in application's main loop:

 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES];
 NSEventType eventType = [event type];
 if (eventType == NSKeyDown)
 {
    my_uint32 keycode = [event keyCode];
    input::doSomeWork(keycode);
 }

Also, I can properly quit an application when a red cross is pressed on the window with the following code:

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
    g_myEngine.stop();
    return NSTerminateNow;
}

But how do I:

a) Catch when a menu item 'Quit MyApplicationName' is chosen?

b) Handle Cmd-Q event?


update: I have added this code:

id menubar = [[NSMenu new] autorelease];
id appMenuItem = [[NSMenuItem new] autorelease];
[menubar addItem:appMenuItem];
[NSApp setMainMenu:menubar];
id appMenu = [[NSMenu new] autorelease];
id appName = [[NSProcessInfo processInfo] processName];
id quitTitle = [@"Quit " stringByAppendingString:appName];
id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
[appMenu addItem:quitMenuItem];
[appMenuItem setSubmenu:appMenu];

and now application exits from the menu, but Cmd-Q still does not work.

like image 423
montonero Avatar asked Feb 06 '12 02:02

montonero


1 Answers

Try setting the menu item's key equivalent modifier mask.

Don't forget to also add menu items for Close Window, Minimize, Hide, Enter/Exit Full Screen, etc., plus the entire Edit menu, including all text-editing features, current and future. (Why the Edit menu? I assume that, at the least, you'll enable the user to name their save games, their high scores (if applicable), or their character. If you have any text editing anywhere in the application, you should support the full Edit menu.)

like image 158
Peter Hosey Avatar answered Sep 23 '22 12:09

Peter Hosey