macosterminatexamarin.macwindowless

Terminating windowless mac application


I am creating my first OS X Application through Xamarin and i have a windowless app, so it's just a icon in the menu bar with an icon and a menu to close the app. I want to close the app through the menuitem with the following code:

public override void DidFinishLaunching (NSNotification notification)
{
    var statusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30f);
    statusItem.Image = NSImage.ImageNamed("os_logo.png");
    statusItem.HighlightMode = true;
    var menu = new NSMenu ();

    // Closing the app
    var quitItem = new NSMenuItem ("Sluit OPEN.dev", "q", delegate {
        NSApplication.SharedApplication.Terminate(NSApplication.SharedApplication);
    });
    menu.AddItem (quitItem);
    NSApplication.SharedApplication.MainMenu = menu;
    statusItem.Menu = menu;
}

But the icon won't disappear/the app won't close.

Does somebody have a solution for this?


Solution

  • You are hiding the event delegate by adding it to a 'non-existent/hidden' SharedApplication menu before you add it to the status menu.

    If you only need it on the status menu item:

    public override void DidFinishLaunching (NSNotification notification)
    {
        var statusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30f);
        statusItem.Image = NSImage.ImageNamed("madmen_icon.jpg");
        statusItem.HighlightMode = true;
    
        var menu = new NSMenu ();
    
        // Closing the app
        var quitItem = new NSMenuItem ("Sluit OPEN.dev ", "q", (s, e) => NSApplication.SharedApplication.Terminate (menu));
        menu.AddItem (quitItem);
    
        statusItem.Menu = menu;
    }
    

    FYI: If you need that same quit menu item on both an application AND status menu then create a brand new NSMenuItem and parent (addItem) it to the app menu as sharing menu items will cause a nice AppKit crash:

    Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Item to be inserted into menu already is in another menu'