Process Cmd-Q in a Cocoa application (and the "Close Application" menu item programmatically)

I created a game application that has only one window. An application is created without the help of .xib files, as described here: How to create a graphical interface and respond to Cocoa events programmatically?

Now I can catch the standard "key up / down" events in the main loop of the application:

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); } 

In addition, I can close the application correctly when the red cross is clicked on the window with the following code:

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

But like me:

a) Catch when the "Exit MyApplicationName" menu item is selected?

b) Handle the Cmd-Q event?


update: I 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 the application exits the menu, but Cmd-Q still does not work.

+4
source share
1 answer

Try setting the menu item key equivalent modifier mask .

Do not forget to add the menu items "Close Window", "Hide", "Hide", "Enter / Exit Full Screen", etc., as well as the entire "Edit" menu, including all text editing functions, current and future . (Why the Edit menu? I assume that at least you allow the user to name their games for saving, their high scores (if applicable) or their nature. If you have text editing anywhere in the application, you should support full Edit menu.)

+2
source

Source: https://habr.com/ru/post/1394942/


All Articles