Menus

for RuBoard

Menus

As a user of Windows applications you should be acquainted with menus, which provide a simple mechanism for choosing commands. In .NET menus are implemented in code. There is no separate resource file.

Step 4: A Menu to Exit the Program

Step 4 of our SimpleForm program illustrates adding a simple menu. File Exit is used to exit the program. See Figure 6-9.

Figure 6-9. A File Exit menu is added to our form (Step 4).

graphics/06fig09.gif

Menu Code

 // SimpleForm.cs - Step 4  ...  private MenuItem menuExit;   private MenuItem menuFile;   private MainMenu mainMenu1;  public Form1()  {     InitializeComponent();     Size = new System.Drawing.Size(300,200);     Text = "Simple Form - Step 4";     x = y = 10;     stdBrush = new SolidBrush(Color.Black);     str = new StringBuilder("Hello, Windows Forms");  }  private void InitializeComponent()  {  mainMenu1 = new MainMenu ();   menuFile = new MenuItem ();   menuExit = new MenuItem ();  // mainMenu1  mainMenu1.MenuItems.Add(menuFile);  // menuFile  menuFile.Index = 0;   menuFile.MenuItems.Add(menuExit);   menuFile.Text = "File";  // menuExit  menuExit.Index = 0;   menuExit.Text = "Exit";   menuExit.Click += new EventHandler(menuExit_Click);   Menu = mainMenu1;  ... 

The code in InitializeComponent builds up the hierarchical menu structure, represented by an instance of the MainMenu class. A menu is composed of MenuItem objects that represent the individual menu commands in the menu structure. Each MenuItem can be a command for your application or a parent menu for other submenu items. You bind the MainMenu to the Form that will display it by assigning the MainMenu to the Menu property of the Form.

When we discuss the Forms Designer later in the chapter, we will see that it is easy to create a menu by dragging a MainMenu control from the toolbox to the form. The Forms Designer will take care of generating appropriate boilerplate code.

Menu Event Code

A delegate is hooked to the event, as with other Windows Forms events. Clicking on a menu item causes the corresponding command to be executed.

 private void InitializeComponent()  {    ...  menuExit.Click +=   new EventHandler(this.menuExit_Click);  ...  }  private void menuExit_Click(object sender,   EventArgs e)   {   Application.Exit();   }  ... 
for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net