Tools Used: .NET Framework, EditPlus.
The following example demonstrates how to add menu item and remove menu items at runtime.
-
-
-
-
-
-
- using System;
- using System.WinForms;
- using System.Drawing;
-
-
-
- class RuntimeMenus:Form
- {
- private MainMenu myMenu;
- private MenuItem mnuFile, mnuExit, mnuRtime;
- private Button btnAdd, btnRemove, btnClose;
- private Graphics g;
- private Font DispFont;
- private SolidBrush MyBrush;
- static int i;
-
-
- public RuntimeMenus()
- {
- InitializeComponents();
- }
- public void InitializeComponents()
- {
- DispFont = new Font("Verdana",8,FontStyle.Bold);
- MyBrush = new SolidBrush(Color.Blue);
-
- myMenu = new MainMenu();
-
- mnuFile = new MenuItem("&File");
- mnuRtime = new MenuItem("&Runtime Menu");
-
- myMenu.MenuItems.Add(mnuFile);
- myMenu.MenuItems.Add(mnuRtime);
-
- mnuExit = new MenuItem("&Exit", new EventHandlerbtnClose_Click),Shortcut.CtrlX);
-
- mnuFile.MenuItems.Add(mnuExit);
-
- btnAdd = new Button();
- btnAdd.Location = new Point(275,20);
- btnAdd.Text = "&Add";
- btnAdd.Click += new EventHandler(btnAdd_Click);
- btnAdd.Size = new Size(100,30);
-
- btnRemove = new Button();
- btnRemove.Location = new Point(275,60);
- btnRemove.Text = "&Remove";
- btnRemove.Click += new EventHandler(btnRemove_Click);
- btnRemove.Size = new Size(100,30);
-
- btnClose = new Button();
- btnClose.Location = new Point(275,100);
- btnClose.Text = "&Close";
- btnClose.Click += new EventHandler(btnClose_Click);
- btnClose.Size = new Size(100,30);
-
- this.Controls.Add(btnAdd);
- this.Controls.Add(btnRemove);
- this.Controls.Add(btnClose);
-
- this.MaximizeBox = false;
- this.MinimizeBox = false;
- this.Text = "Creating Menus on the Fly";
- this.Menu = myMenu;
- this.Size = new Size(400,250);
- this.CancelButton = btnClose;
- this.StartPosition = FormStartPosition.CenterScreen;
-
- g = Graphics.FromHWND(this.Handle);
- }
-
- protected void btnAdd_Click(object sender, EventArgs e)
- {
- mnuRtime.MenuItems.Add("Runtime Menu " + (i+1), new EventHandler mnuRtime_Click));
- g.Clear(Color.FromA#d8d0c8);
- g.DrawString("Runtime Menu " + (i + 1) + " added Successfully",DispFont,MyBrush,50,150);
- i++;
- }
-
- protected void btnRemove_Click(object sender, EventArgs e)
- {
- if (i <= 0)
- {
- g.Clear(Color.FromA#d8d0c8);
- g.DrawString("Menu is Empty",DispFont, MyBrush,125,150);
- }
- else
- {
- mnuRtime.MenuItems.Remove(i-1);
- g.Clear(Color.FromA#d8d0c8);
- g.DrawString("Runtime Menu " + (i) + " Removed Successfully",DispFont,MyBrush,50,150);
- i=i-1;
- }
- }
-
- protected void mnuRtime_Click(object sender, EventArgs e)
- {
- String s = sender.ToString();
- MessageBox.Show("You Clicked " + s.Substring(28), "RunTime Menu", MessageBox.IconInformation);
- }
-
- protected void btnClose_Click(object sender, EventArgs e)
- {
- Application.Exit();
- }
-
- public static void Main()
- {
- Application.Run(new RuntimeMenus());
- }
- }