Monday, 13 February 2012

MonoMac - Getting started with Main Menu Items

Following on from the last post, here is a quick example demonstrating how to add a new items to the application Main Menu. Here we explore using the AppDelegate to pass a NSMenuItem Action to the MainWindowController.

1. Create an Empty project

Create a new MonoMac Project and double click on MainMenu.xib

2. Configure Xcode

From Xcode click the button in the bottom left ("Show Document Outline") and expand the Main Menu:

3. Create the new NSMenuItem place holder

Drag a NSMenuItem from the Object Library and drop it below the "Menu Item - Help" object:

4. Create the Drop down menu

Drag a NSMenu onto the NSMenuItem created in step 3 and set the title of the NSMenu to "My Menu" and the title of the first NSMenuItem to be "MenuTest":

5. Create the NSMenuItem Action

Display the AppDelegate.h file and then hold down [ctrl] and drag the "MenuTest" NSMenuItem onto the code window. Change the Connection to "Action", the Name to _MenuTestClick and then press connect:

6.  Add a label to the MainWindow

Select MainWindow.xib (via the navigation  menu at the top of xcode) and add a label. Create an outlet by holding down [ctrl] and drag it onto the MainWindowController.h. Call the outlet _Label1:

See the hello-os-x-from-c-five-steps example for more detailed steps on adding label outlets ro rge MainWindowController.h file.

Save Changes and move back to MonoDevelop.

7. One small bit of coding

From Mono Develop, Open MainWindowController.cs  and add this method:

public void MenuTestClick()
    _Label1.StringValue = "Menu Clicked!";

Open AppDelegate.cs and complete the implementation of the partial method _MenuTestClick (see the designer for the implementation of this partial method):

partial void _MenuTestClick (MonoMac.Foundation.NSObject sender)

Now Build and run the application:

Marvellous, a working Main Menu!