Add Menu to Form : Menu « GUI Windows Forms « C# / CSharp Tutorial






Add Menu to Form
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class FormWithMenu : System.Windows.Forms.Form
{
  private MainMenu mainMenu;

  private System.ComponentModel.Container components = null;

  public FormWithMenu()
  {
    InitializeComponent();

    mainMenu = new MainMenu();

    MenuItem miFile = mainMenu.MenuItems.Add("&File");          
    miFile.MenuItems.Add(new MenuItem("E&xit", new EventHandler(this.FileExit_Clicked), Shortcut.CtrlX));
    
    MenuItem miHelp = mainMenu.MenuItems.Add("Help");
    miHelp.MenuItems.Add(new MenuItem("&About",  new EventHandler(this.HelpAbout_Clicked),Shortcut.CtrlA));

    this.Menu = mainMenu;

    mainMenu.GetForm().BackColor = Color.Black;
  }

  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }

  private void InitializeComponent()
  {
    this.components = new System.ComponentModel.Container();
    this.Size = new System.Drawing.Size(300,300);
    this.Text = "Form1";
  }

  private void FileExit_Clicked(object sender, EventArgs e) 
  {
    this.Close();
  }
    
  private void HelpAbout_Clicked(object sender, EventArgs e) 
  {
    MessageBox.Show("Help");
  }

  [STAThread]
  static void Main() 
  {
    Application.Run(new FormWithMenu());
  }
}








23.39.Menu
23.39.1.Add Menu to FormAdd Menu to Form
23.39.2.Create a Menu without using the IDECreate a Menu without using the IDE
23.39.3.Menu RightToLeftMenu RightToLeft
23.39.4.Add SubmenuAdd Submenu
23.39.5.Set Label text in menu actionSet Label text in menu action
23.39.6.Context Menu Demo
23.39.7.Context Menu Using Add
23.39.8.Add MenuStrip and ToolStripMenuItem to Form