2

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
dylanvdb
  • 106
  • 18

1 Answers1

1

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'

pkamb
  • 33,281
  • 23
  • 160
  • 191
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • Thanks for the solution and the explanation! – dylanvdb Aug 13 '15 at 01:53
  • @SushiHangover Do you know _why_ AppKit doesn't like the same menu item in two different menus? We have a case where we want _exactly_ the same item (same name, same key equivalent, same action, etc.) so it made so much sense to use the same object. Until we got the crash that is... – Cem Schemel Jan 19 '19 at 00:43