Create a Menu without using the IDE : Menu « GUI Windows Forms « C# / CSharp Tutorial






Create a Menu without using the IDE
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

public class MenuCreationManually : System.Windows.Forms.Form
{
    void ShowInfo(Object Sender,EventArgs e)
    {
        MenuItem item=(MenuItem)Sender;
        switch(item.Text)
        {
            case "&Open":
                Console.WriteLine("Open a file from disk");
            break;
            case "&Save":
                Console.WriteLine("Save a file onto disk");
            break;
            case "E&xit":
                Console.WriteLine("Exit MenuApp");
            break;
        }
    }

    public MenuCreationManually()
    {
        this.MaximizeBox = true;
        this.FormBorderStyle = FormBorderStyle.Sizable;

        MainMenu menu = new MainMenu();

        

        MenuItem filemenu = new MenuItem();
        filemenu.Text = "&File";
        menu.MenuItems.Add(filemenu);

            MenuItem open = new MenuItem();
            open.Text = "&Open";
            open.Select += new EventHandler(ShowInfo);
            filemenu.MenuItems.Add(open);

            MenuItem save= new MenuItem();
            save.Text = "&Save";
            save.Select += new EventHandler(ShowInfo);
            filemenu.MenuItems.Add(save);


            MenuItem exit= new MenuItem();
            exit.Text = "E&xit";
            exit.Select += new EventHandler(ShowInfo);
            filemenu.MenuItems.Add(exit);
    
        this.Menu = menu;

        ContextMenu cmenu = new ContextMenu();
        cmenu.MenuItems.Add(new MenuItem("&First"));
        cmenu.MenuItems.Add(new MenuItem("&Second"));
        cmenu.MenuItems.Add(new MenuItem("-"));
        cmenu.MenuItems.Add(new MenuItem("&Third"));

        this.ContextMenu=cmenu;
    }

    static void Main()
    {
        Application.Run(new MenuCreationManually());
    }
}








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