Tuesday, 31 January 2012

Hello OS X from C# (Five Steps)

Here is a gentle introduction to developing OS X applications with C#. Hopefully this is useful and gets some more people started with the technology.

To start with, I'm brushing over the technology, the philosophy of design patterns like MVC and how the nuts and bolts work - this is a quick and dirty guide to getting stuck into a simple hello world style application with minimal effort.

Before I begin, there are some prerequisites:

- OS X operating system - I currently use OS X Lion running on a Macbook Pro.
- Mono 2.10.8
- MonoDevelop 2.8

XCode, Mono and MonoDevelop are available to download for free and they all installed fine on my mac.

1. Create a Project

Open MonoDevelop and goto File -> New -> Solution:

Select a MonoMac Project, give it an appropriate Name and select Forward and the OK  on the project features tab.

Marvellous, we now have a project:

Check it works by right clicking on the project and selecting Run Item:

Exciting eh?

Let's get back to the task in hand. Stop the application from running by going to Run -> Stop.

2. Design the Graphical User Interface (GUI)

Double click on MainWindow.xib and wait for Xcode to open:

In the botton right hand corner is the Object Library (at least on my setup). Drag a NSButton and a NSTextField onto the Window.

Now press the Show the Assistant Editor button to get the hybrid view of the Window and the Code editor:

At the top of the code window there are arrow buttons, use them to cycle through the code files until MainWindowController.h is displayed.

3. Add the Label Outlet

Select the NSTextField on our Window, hold down the [ctrl] button and drag onto the code window. In the Popup window set the Name to be _Label1:

Now press the Connect button and the code should look like this:

@interface MainWindowController : NSWindowController {
    IBOutlet NSTextField *_Label1;

4. Add the Button Action

Select the NSButton on our Window, hold down the [ctrl] button and drag to the code window. Change the Connection to Action, the Name to _ButtonClick. The Type box should automatically change to id.

So the Code should now resemble:

@interface MainWindowController : NSWindowController {
    IBOutlet NSTextField *_Label1;
- (IBAction)_ButtonClick:(id)sender;


Save (File -> Save) and then go back into MonoDevelop.

5. Wiring up the Button Click Event

When MonoDevelop is refocused it should update it's code files form the changes made in Xcode.

Double click MainWindowController.cs and add the following method:

partial void _ButtonClick(NSObject sender)
         _Label1.StringValue = "Hello";

So in the editor it looks like this:

Now run the application again and press the button:

So as you can see, it's actually quite easy.