Sunday, August 16, 2009

WinForms on Mac

MSDN has concise examples of the use of C# UI components such as this showing TextBox and GroupBox. I changed this code to display the contents of a Generic stack (mostly to verify Mono can really do Windows on the Mac).

As you can see, Mono does do Windows on the Mac. The Generics in this example work exactly as Java's do but I've heard that C#'s are generally thought to be better designed. I used namespaces and developed the application in one source file. The commands to compile and run the code follow the source shown here:
using System;
using System.Windows.Forms;
using System.Drawing;

namespace NotepadForms { 

  public class StackForm : Form
  {
      public StackForm(GenericStack.Stack s)
      {
          GroupBox groupBox = new GroupBox();
          groupBox.Height = ( 1 + s.getSize()) * 22; 
          TextBox[] textBox = new TextBox[s.getSize()];
          for (int i=0;i < s.getSize(); i++) { 
              textBox[i] = new TextBox(); 
              textBox[i].Location = new Point(15, 20 * (i+1));
              textBox[i].Text = s.Pop().ToString();
              groupBox.Controls.Add(textBox[i]);
          } 
          // Set the Text and Dock properties of the GroupBox.
          groupBox.Text = "MyGroupBox";
          groupBox.Dock = DockStyle.Top;

          // Disable the GroupBox (which disables all its child controls)
          groupBox.Enabled = true;

          // Add the Groupbox to the form.
          this.Controls.Add(groupBox);
      } 
      [STAThread] 
      static void Main()
      {
         int[] ary = {1,2,3,4,5,6,7,8,9};
         GenericStack.Stack s = new GenericStack.Stack(ary);
         Application.Run(new StackForm(s));
      }
  }
}
  
namespace GenericStack {
   public class Stack 
   { 
      T[] StackArray; 
      int StackCursor = 0; 
      public int StackSize; 

      public void Push(T x) { 
         if ( !StackIsFull ) 
            StackArray[StackCursor++] = x; 
      } 
      public T Pop() { 
         return ( !StackIsEmpty ) 
            ? StackArray[--StackCursor] 
            : StackArray[0]; 
      } 

      bool StackIsFull  { get{ return StackCursor >= StackSize; } } 
      bool StackIsEmpty { get{ return StackCursor <= 0; } } 

      public int getSize() {
          return StackSize;
      }

      public Stack(T[] initVal) { 
         StackSize = initVal.Length;
         StackArray = new T[StackSize]; 
         foreach(T y in initVal) {
            Push(y);
         }
      } 

      public void Print() { 
         for (int i = StackCursor -1; i >= 0 ; i--) 
            Console.WriteLine("   Value: {0}", StackArray[i]); 
      } 
   } 
}
[greg:mono] gmcs -r:System.Windows.Forms.dll -r:System.Drawing.dll StackForm.cs
[greg:mono] mono StackForm.exe