Owner Drawn Menu Control



   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/
using System.Drawing;

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Text;

namespace OwnerDrawnMenuControl
{
  /// <summary>
  /// Summary description for OwnerDrawnMenuControl.
  /// </summary>
  public class OwnerDrawnMenuControl : System.Windows.Forms.Form
  {
    internal System.Windows.Forms.MainMenu mainMenu1;
    internal System.Windows.Forms.MenuItem mnuFile;
    internal System.Windows.Forms.MenuItem mnuFonts;
    internal System.Windows.Forms.ImageList imgMenu;
    private System.ComponentModel.IContainer components;

    public OwnerDrawnMenuControl()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(OwnerDrawnMenuControl));
      this.mainMenu1 = new System.Windows.Forms.MainMenu();
      this.mnuFile = new System.Windows.Forms.MenuItem();
      this.mnuFonts = new System.Windows.Forms.MenuItem();
      this.imgMenu = new System.Windows.Forms.ImageList(this.components);
      // 
      // mainMenu1
      // 
      this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.mnuFile});
      // 
      // mnuFile
      // 
      this.mnuFile.Index = 0;
      this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                          this.mnuFonts});
      this.mnuFile.Text = "File";
      // 
      // mnuFonts
      // 
      this.mnuFonts.Index = 0;
      this.mnuFonts.Text = "Fonts";
      // 
      // imgMenu
      // 
      this.imgMenu.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
      this.imgMenu.ImageSize = new System.Drawing.Size(16, 16);
      this.imgMenu.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgMenu.ImageStream")));
      this.imgMenu.TransparentColor = System.Drawing.Color.Transparent;
      // 
      // OwnerDrawnMenuControl
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Menu = this.mainMenu1;
      this.Name = "OwnerDrawnMenuControl";
      this.Text = "MenuControlClient";
      this.Load += new System.EventHandler(this.OwnerDrawnMenuControl_Load);

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new OwnerDrawnMenuControl());
    }

    private void OwnerDrawnMenuControl_Load(object sender, System.EventArgs e)
    {
      mnuFile.MenuItems.Add(new ImageMenuItem("New", imgMenu.Images[0]));
      mnuFile.MenuItems.Add(new ImageMenuItem("Open", imgMenu.Images[1]));
      mnuFile.MenuItems.Add(new ImageMenuItem("Save", imgMenu.Images[2]));
      
      InstalledFontCollection fonts = new InstalledFontCollection();
      
      foreach (FontFamily family in fonts.Families)
      {
        try
        {
          mnuFonts.MenuItems.Add(new ImageMenuItem(family.Name,
                           new Font(family, 10), null, Color.CornflowerBlue));
        }
        catch
        {
          // Catch invalid fonts/styles and ignore them.
        }
      }

    }
  }
    public class ImageMenuItem : MenuItem
    {
        private Font font;
        private Color foreColor;
        private Image image;
        
        public Font Font
        {
            get
            {
                return font;
            }
            set
            {
                font = value;
            }
        }
        
        public Image Image
        {
            get
            {
                return image;
            }
            set
            {
                image = value;
            }
        }

        public Color ForeColor
        {
            get
            {
                return foreColor;
            }
            set
            {
                foreColor = value;
            }
        }
        
        public ImageMenuItem(string text, Font font, Image image, Color foreColor) : base(text)
        {
            this.Font = font;
            this.Image = image;
            this.ForeColor = foreColor;
            this.OwnerDraw = true;
        }
    
        public ImageMenuItem(string text, Image image) : base(text)
        {
            // Choose a suitable default color and font.
            this.Font = new Font("Tahoma", 8);
            this.Image = image;
            this.ForeColor = SystemColors.MenuText;
            this.OwnerDraw = true;
        }
        
        protected override void OnMeasureItem(System.Windows.Forms.MeasureItemEventArgs e)
        {
            base.OnMeasureItem(e);
            
            // Measure size needed to display text.
            e.ItemHeight = (int)e.Graphics.MeasureString(this.Text, this.Font).Height + 5;
            e.ItemWidth = (int)e.Graphics.MeasureString(this.Text, this.Font).Width + 30;
        }
        
        protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
        {
            base.OnDrawItem(e);

            // Determine whether disabled text is needed.
            Color textColor;
            if (this.Enabled == false)
            {
                textColor = SystemColors.GrayText;
            }
            else
            {
                e.DrawBackground();
                if ((e.State &amp; DrawItemState.Selected) == DrawItemState.Selected)
                {
                    textColor = SystemColors.HighlightText;
                }
                else
                {
                    textColor = this.ForeColor;
                }
            }
    

            // Draw the image.
            if (Image != null)
            {
                if (this.Enabled == false)
                {
                    ControlPaint.DrawImageDisabled(e.Graphics, Image,
                        e.Bounds.Left + 3, e.Bounds.Top + 2, SystemColors.Menu);
                }
                else
                {
                    e.Graphics.DrawImage(Image, e.Bounds.Left + 3, e.Bounds.Top + 2);
                }
            }
            
            // Draw the text with the supplied colors and in the set region.
            e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(textColor),
                e.Bounds.Left + 25, e.Bounds.Top + 3);

        }
    }
         

  
}


           
          


OwnerDrawnMenuControl.zip( 35 k)

Owner Drawn Menu



   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace OwnerDrawnMenu
{
  /// <summary>
  /// Summary description for OwnerDrawnMenu.
  /// </summary>
  public class OwnerDrawnMenu : System.Windows.Forms.Form
  {
    internal System.Windows.Forms.ImageList imgMenu;
    internal System.Windows.Forms.MainMenu mainMenu1;
    internal System.Windows.Forms.MenuItem mnuFile;
    internal System.Windows.Forms.MenuItem mnuNew;
    internal System.Windows.Forms.MenuItem mnuOpen;
    internal System.Windows.Forms.MenuItem mnuSave;
    private System.ComponentModel.IContainer components;

    public OwnerDrawnMenu()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(OwnerDrawnMenu));
      this.imgMenu = new System.Windows.Forms.ImageList(this.components);
      this.mainMenu1 = new System.Windows.Forms.MainMenu();
      this.mnuFile = new System.Windows.Forms.MenuItem();
      this.mnuNew = new System.Windows.Forms.MenuItem();
      this.mnuOpen = new System.Windows.Forms.MenuItem();
      this.mnuSave = new System.Windows.Forms.MenuItem();
      // 
      // imgMenu
      // 
      this.imgMenu.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
      this.imgMenu.ImageSize = new System.Drawing.Size(16, 16);
      this.imgMenu.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgMenu.ImageStream")));
      this.imgMenu.TransparentColor = System.Drawing.Color.Transparent;
      // 
      // mainMenu1
      // 
      this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                            this.mnuFile});
      // 
      // mnuFile
      // 
      this.mnuFile.Index = 0;
      this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                          this.mnuNew,
                                          this.mnuOpen,
                                          this.mnuSave});
      this.mnuFile.Text = "File";
      // 
      // mnuNew
      // 
      this.mnuNew.Index = 0;
      this.mnuNew.OwnerDraw = true;
      this.mnuNew.Text = "New";
      this.mnuNew.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.mnu_DrawItem);
      this.mnuNew.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.mnu_MeasureItem);
      // 
      // mnuOpen
      // 
      this.mnuOpen.Index = 1;
      this.mnuOpen.OwnerDraw = true;
      this.mnuOpen.Text = "Open";
      this.mnuOpen.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.mnu_DrawItem);
      this.mnuOpen.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.mnu_MeasureItem);
      // 
      // mnuSave
      // 
      this.mnuSave.Index = 2;
      this.mnuSave.OwnerDraw = true;
      this.mnuSave.Text = "Save";
      this.mnuSave.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.mnu_DrawItem);
      this.mnuSave.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.mnu_MeasureItem);
      // 
      // OwnerDrawnMenu
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Menu = this.mainMenu1;
      this.Name = "OwnerDrawnMenu";
      this.Text = "Owner-Drawn Menu";

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new OwnerDrawnMenu());
    }

    private void mnu_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
    {
      // Retrieve current item.
      MenuItem mnuItem = (MenuItem)sender;

      Font menuFont = new Font("Tahoma", 8);

      // Measure size needed to display text.
      // We add 30 pixels to the width to allow a generous spacing for the image.
      e.ItemHeight = (int)e.Graphics.MeasureString(mnuItem.Text, menuFont).Height + 5;
            e.ItemWidth = (int)e.Graphics.MeasureString(mnuItem.Text, menuFont).Width + 30;
    }

    private void mnu_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
    {
      // Retrieve current item.
      MenuItem mnuItem = (MenuItem)sender;
        
      // This defaults to the highlighted background if selected.
      e.DrawBackground();
            
      // Retrieve the image from an ImageList control.
      Image menuImage = imgMenu.Images[mnuItem.Index];
      
      // Draw the image.
      e.Graphics.DrawImage(menuImage, e.Bounds.Left + 3, e.Bounds.Top + 2);
      
      // Draw the text with the supplied colors and in the set region.
      e.Graphics.DrawString(mnuItem.Text, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left + 25, e.Bounds.Top + 3);
    }
  }
}


           
          


OwnerDrawnMenu.zip( 28 k)

Add Help text for MenuItem

   
 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class MenuItemHelp: MenuItem
{
     StatusBarPanel sbpHelpPanel;
     string         strHelpText;

     public MenuItemHelp(string strText): base(strText)
     {
     }
     public StatusBarPanel HelpPanel
     {
          get { return sbpHelpPanel; }
          set { sbpHelpPanel = value; }
     }
     public string HelpText
     {
          get { return strHelpText; }
          set { strHelpText = value; }
     }
     protected override void OnSelect(EventArgs ea)
     {
          base.OnSelect(ea);
   
          if (HelpPanel != null)
               HelpPanel.Text = HelpText;
     }
}


class MenuHelpSubclass: Form
{
     StatusBarPanel sbpMenuHelp;
     string         strSavePanelText;
   
     public static void Main()
     {
          Application.Run(new MenuHelpSubclass());
     }
     public MenuHelpSubclass()
     {

          StatusBar sb = new StatusBar();
          sb.Parent = this;
          sb.ShowPanels = true;
   
          sbpMenuHelp = new StatusBarPanel();
          sbpMenuHelp.Text = "Ready";
          sbpMenuHelp.AutoSize = StatusBarPanelAutoSize.Spring;
   
          sb.Panels.Add(sbpMenuHelp);
   
          Menu = new MainMenu();
          
          MenuItemHelp mi = new MenuItemHelp("&amp;File");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Commands for working with files";
          Menu.MenuItems.Add(mi);
   
          mi = new MenuItemHelp("&amp;Open...");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Opens an existing document";
          Menu.MenuItems[0].MenuItems.Add(mi);
          
          mi = new MenuItemHelp("&amp;Close");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Closes the current document";
          Menu.MenuItems[0].MenuItems.Add(mi);
   
          mi = new MenuItemHelp("&amp;Save");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Saves the current document";
          Menu.MenuItems[0].MenuItems.Add(mi);
   
          mi = new MenuItemHelp("&amp;Edit");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Commands for editing the document";
          Menu.MenuItems.Add(mi);
   
          mi = new MenuItemHelp("Cu&amp;t");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Deletes the selection and " +
                        "copies it to the clipboard";
          Menu.MenuItems[1].MenuItems.Add(mi);
          
          mi = new MenuItemHelp("&amp;Copy");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Copies the selection to the clipboard";
          Menu.MenuItems[1].MenuItems.Add(mi);
   
          mi = new MenuItemHelp("&amp;Paste");
          mi.HelpPanel = sbpMenuHelp;
          mi.HelpText = "Replaces the current selection " +
                        "with the clipboard contents";
          Menu.MenuItems[1].MenuItems.Add(mi);
     }
     protected override void OnMenuStart(EventArgs ea)
     {
          strSavePanelText = sbpMenuHelp.Text;
     }
     protected override void OnMenuComplete(EventArgs ea)
     {
          sbpMenuHelp.Text = strSavePanelText;
     }
}

    


Help Menu

   
 
using System;
using System.Drawing;
using System.Windows.Forms;
   
class HelpMenu: Form
{
     Bitmap bmHelp;
   
     public static void Main()
     {
          Application.Run(new HelpMenu());
     }
     public HelpMenu()
     {
          bmHelp = new Bitmap(GetType(), "help.bmp");
   
          Menu = new MainMenu();
          Menu.MenuItems.Add("&amp;Help");
   
          MenuItem mi     = new MenuItem("&amp;Help");
          mi.OwnerDraw    = true;
          mi.Click       += new EventHandler(MenuHelpOnClick);
          mi.DrawItem    += new DrawItemEventHandler(MenuHelpOnDrawItem);
          mi.MeasureItem += new MeasureItemEventHandler(MenuHelpOnMeasureItem);
   
          Menu.MenuItems[0].MenuItems.Add(mi);
     }
     void MenuHelpOnMeasureItem(object obj, MeasureItemEventArgs miea)
     {
          miea.ItemWidth  = bmHelp.Width;
          miea.ItemHeight = bmHelp.Height;
     }
     void MenuHelpOnDrawItem(object obj, DrawItemEventArgs diea)
     {
          Rectangle rect = diea.Bounds;
          rect.X += diea.Bounds.Width - bmHelp.Width;
          rect.Width = bmHelp.Width;
   
          diea.DrawBackground();
          diea.Graphics.DrawImage(bmHelp, rect);
     }
     void MenuHelpOnClick(object obj, EventArgs ea)
     {
          MessageBox.Show("Help", Text);
     }
}

    


Add a Main Menu


   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Add a Main Menu. 
 
using System; 
using System.Windows.Forms; 
 
public class MenuForm : Form { 
  MainMenu MyMenu; 
 
  public MenuForm() { 
    Text = "Adding a Main Menu"; 
 
    // Create a main menu object. 
    MyMenu  = new MainMenu(); 
 
    // Add top-level menu items to the menu. 
    MenuItem m1 = new MenuItem("File"); 
    MyMenu.MenuItems.Add(m1); 
 
    MenuItem m2 = new MenuItem("Tools"); 
    MyMenu.MenuItems.Add(m2); 
 
    // Create File submenu 
    MenuItem subm1 = new MenuItem("Open"); 
    m1.MenuItems.Add(subm1); 
 
    MenuItem subm2 = new MenuItem("Close"); 
    m1.MenuItems.Add(subm2); 
 
    MenuItem subm3 = new MenuItem("Exit"); 
    m1.MenuItems.Add(subm3); 
 
    // Create Tools submenu 
    MenuItem subm4 = new MenuItem("Coordinates"); 
    m2.MenuItems.Add(subm4); 
 
    MenuItem subm5 = new MenuItem("Change Size"); 
    m2.MenuItems.Add(subm5); 
 
    MenuItem subm6 = new MenuItem("Restore"); 
    m2.MenuItems.Add(subm6); 
 
 
    // Add event handlers for the menu items. 
    subm1.Click += new EventHandler(MMOpenClick); 
    subm2.Click += new EventHandler(MMCloseClick); 
    subm3.Click += new EventHandler(MMExitClick); 
    subm4.Click += new EventHandler(MMCoordClick); 
    subm5.Click += new EventHandler(MMChangeClick); 
    subm6.Click += new EventHandler(MMRestoreClick); 
 
    // Assign the menu to the form. 
    Menu = MyMenu; 
  }   
 
  [STAThread] 
  public static void Main() { 
    MenuForm skel = new MenuForm(); 
 
    Application.Run(skel); 
  } 
 
  // Handler for main menu Coordinates selection. 
  protected void MMCoordClick(object who, EventArgs e) { 
    // Create a string that contains the cooridinates. 
    string size = 
      String.Format("{0}: {1}, {2}
{3}: {4}, {5} ", 
                    "Top, Left", Top, Left, 
                    "Bottom, Right", Bottom, Right); 
 
    // Display a message box. 
    MessageBox.Show(size, "Window Coordinates", 
                    MessageBoxButtons.OK); 
  } 
 
  // Handler for main menu Change selection. 
  protected void MMChangeClick(object who, EventArgs e) { 
    Width = Height = 200; 
  } 
 
  // Handler for main menu Restore selection. 
  protected void MMRestoreClick(object who, EventArgs e) { 
    Width = Height = 300; 
  } 
 
  // Handler for main menu Open selection. 
  protected void MMOpenClick(object who, EventArgs e) { 
 
    MessageBox.Show("Inactive", "Inactive", 
                    MessageBoxButtons.OK); 
  } 
 
  // Handler for main menu Open selection. 
  protected void MMCloseClick(object who, EventArgs e) { 
 
    MessageBox.Show("Inactive", "Inactive", 
                    MessageBoxButtons.OK); 
  } 
 
  // Handler for main menu Exit selection. 
  protected void MMExitClick(object who, EventArgs e) { 
 
    DialogResult result = MessageBox.Show("Stop Program?", 
                            "Terminate", 
                             MessageBoxButtons.YesNo); 
 
    if(result == DialogResult.Yes) Application.Exit(); 
  } 
}


           
          


Menu Text Provider Host


   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace ExtenderProviderHost
{
    /// <summary>
    /// Summary description for MenuTextProviderHost.
    /// </summary>
    public class MenuTextProviderHost : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.MainMenu mnuMain;
        internal System.Windows.Forms.MenuItem MenuItem1;
        internal System.Windows.Forms.MenuItem mnuNew;
        internal System.Windows.Forms.MenuItem mnuOpen;
        internal System.Windows.Forms.MenuItem mnuSave;
        private MenuTextProvider menuTextProvider1;
        internal System.Windows.Forms.GroupBox GroupBox1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public MenuTextProviderHost()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mnuMain = new System.Windows.Forms.MainMenu();
            this.MenuItem1 = new System.Windows.Forms.MenuItem();
            this.mnuNew = new System.Windows.Forms.MenuItem();
            this.mnuOpen = new System.Windows.Forms.MenuItem();
            this.mnuSave = new System.Windows.Forms.MenuItem();
            this.menuTextProvider1 = new MenuTextProvider();
            this.GroupBox1 = new System.Windows.Forms.GroupBox();
            this.SuspendLayout();
            // 
            // mnuMain
            // 
            this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.MenuItem1});
            // 
            // MenuItem1
            // 
            this.MenuItem1.Index = 0;
            this.MenuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                      this.mnuNew,
                                                                                      this.mnuOpen,
                                                                                      this.mnuSave});
            this.MenuItem1.Text = "File";
            // 
            // mnuNew
            // 
            this.mnuNew.Index = 0;
            this.mnuNew.Text = "New";
            // 
            // mnuOpen
            // 
            this.mnuOpen.Index = 1;
            this.mnuOpen.Text = "Open";
            // 
            // mnuSave
            // 
            this.mnuSave.Index = 2;
            this.mnuSave.Text = "Save";
            // 
            // menuTextProvider1
            // 
            this.menuTextProvider1.Location = new System.Drawing.Point(0, 244);
            this.menuTextProvider1.Name = "menuTextProvider1";
            this.menuTextProvider1.Size = new System.Drawing.Size(292, 22);
            this.menuTextProvider1.TabIndex = 0;
            this.menuTextProvider1.Text = "menuTextProvider1";
            // 
            // GroupBox1
            // 
            this.GroupBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.GroupBox1.Location = new System.Drawing.Point(0, 240);
            this.GroupBox1.Name = "GroupBox1";
            this.GroupBox1.Size = new System.Drawing.Size(292, 4);
            this.GroupBox1.TabIndex = 2;
            this.GroupBox1.TabStop = false;
            this.GroupBox1.Text = "GroupBox1";
            // 
            // MenuTextProviderHost
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.GroupBox1,
                                                                          this.menuTextProvider1});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Menu = this.mnuMain;
            this.Name = "MenuTextProviderHost";
            this.Text = "MenuTextProviderHost";
            this.Load += new System.EventHandler(this.MenuTextProviderHost_Load);
            this.ResumeLayout(false);

        }
        #endregion

        private void MenuTextProviderHost_Load(object sender, System.EventArgs e)
        {
            menuTextProvider1.SetHelpText(mnuNew, " Create a new document and abandon the current one.");
        }

        static void Main() 
        {
            Application.Run(new MenuTextProviderHost());
        }
    }
    [ProvideProperty("HelpText", typeof(string))]
    public class MenuTextProvider : StatusBar, IExtenderProvider
    {
        public bool CanExtend(object extendee)
        {
            if (extendee.GetType() == typeof(MenuItem))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private Hashtable helpText = new Hashtable();

        public void SetHelpText(object extendee, string value)
        {
            // Specifying an empty value removes the extension.
            if (value == "")
            {
                helpText.Remove(extendee);
                MenuItem mnu = (MenuItem)extendee;
                mnu.Select -= new EventHandler(MenuSelect);
            }
            else
            {
                helpText[extendee] = value;
                MenuItem mnu = (MenuItem)extendee;
                mnu.Select += new EventHandler(MenuSelect);
            }
        }

        public string GetHelpText(object extendee)
        {
            if (helpText[extendee] != null)
            {
                return helpText[extendee].ToString();
            }
            else
            {
                return string.Empty;
            }
            }

            private void MenuSelect(object sender, System.EventArgs e)
            {
                this.Text = helpText[sender].ToString();
            }

    }




}


           
          


Dynamic Menu

   

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/

using System.Data.SqlClient;

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace DynamicMenu
{
    /// <summary>
    /// Summary description for DynamicMenu.
    /// </summary>
    public class DynamicMenu : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.MainMenu mnuMain;
        internal System.Windows.Forms.MenuItem mnuFile;
        internal System.Windows.Forms.MenuItem mnuNew;
        internal System.Windows.Forms.MenuItem mnuOpen;
        internal System.Windows.Forms.MenuItem mnuClose;
        internal System.Windows.Forms.MenuItem mnuSave;
        internal System.Windows.Forms.MenuItem MenuItem12;
        internal System.Windows.Forms.MenuItem mnuExit;
        internal System.Windows.Forms.MenuItem mnuTools;
        internal System.Windows.Forms.MenuItem mnuManageHardware;
        internal System.Windows.Forms.MenuItem mnuSetupUserAccounts;
        internal System.Windows.Forms.MenuItem mnuChangeDisplay;
        internal System.Windows.Forms.MenuItem mnuHelp;
        internal System.Windows.Forms.MenuItem mnuContents;
        internal System.Windows.Forms.MenuItem MenuItem13;
        internal System.Windows.Forms.MenuItem mnuAbout;
        internal System.Windows.Forms.Button cmdAdmin;
        internal System.Windows.Forms.Button cmdUser;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public DynamicMenu()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mnuMain = new System.Windows.Forms.MainMenu();
            this.mnuFile = new System.Windows.Forms.MenuItem();
            this.mnuNew = new System.Windows.Forms.MenuItem();
            this.mnuOpen = new System.Windows.Forms.MenuItem();
            this.mnuClose = new System.Windows.Forms.MenuItem();
            this.mnuSave = new System.Windows.Forms.MenuItem();
            this.MenuItem12 = new System.Windows.Forms.MenuItem();
            this.mnuExit = new System.Windows.Forms.MenuItem();
            this.mnuTools = new System.Windows.Forms.MenuItem();
            this.mnuManageHardware = new System.Windows.Forms.MenuItem();
            this.mnuSetupUserAccounts = new System.Windows.Forms.MenuItem();
            this.mnuChangeDisplay = new System.Windows.Forms.MenuItem();
            this.mnuHelp = new System.Windows.Forms.MenuItem();
            this.mnuContents = new System.Windows.Forms.MenuItem();
            this.MenuItem13 = new System.Windows.Forms.MenuItem();
            this.mnuAbout = new System.Windows.Forms.MenuItem();
            this.cmdAdmin = new System.Windows.Forms.Button();
            this.cmdUser = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // mnuMain
            // 
            this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuFile,
                                                                                    this.mnuTools,
                                                                                    this.mnuHelp});
            // 
            // mnuFile
            // 
            this.mnuFile.Index = 0;
            this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuNew,
                                                                                    this.mnuOpen,
                                                                                    this.mnuClose,
                                                                                    this.mnuSave,
                                                                                    this.MenuItem12,
                                                                                    this.mnuExit});
            this.mnuFile.Text = "File";
            // 
            // mnuNew
            // 
            this.mnuNew.Index = 0;
            this.mnuNew.Text = "New";
            // 
            // mnuOpen
            // 
            this.mnuOpen.Index = 1;
            this.mnuOpen.Text = "Open";
            // 
            // mnuClose
            // 
            this.mnuClose.Index = 2;
            this.mnuClose.Text = "Close";
            // 
            // mnuSave
            // 
            this.mnuSave.Index = 3;
            this.mnuSave.Text = "Save";
            // 
            // MenuItem12
            // 
            this.MenuItem12.Index = 4;
            this.MenuItem12.Text = "-";
            // 
            // mnuExit
            // 
            this.mnuExit.Index = 5;
            this.mnuExit.Text = "Exit";
            // 
            // mnuTools
            // 
            this.mnuTools.Index = 1;
            this.mnuTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                     this.mnuManageHardware,
                                                                                     this.mnuSetupUserAccounts,
                                                                                     this.mnuChangeDisplay});
            this.mnuTools.Text = "Tools";
            // 
            // mnuManageHardware
            // 
            this.mnuManageHardware.Index = 0;
            this.mnuManageHardware.Text = "Manage Hardware";
            // 
            // mnuSetupUserAccounts
            // 
            this.mnuSetupUserAccounts.Index = 1;
            this.mnuSetupUserAccounts.Text = "Setup User Accounts";
            // 
            // mnuChangeDisplay
            // 
            this.mnuChangeDisplay.Index = 2;
            this.mnuChangeDisplay.Text = "Change Display";
            // 
            // mnuHelp
            // 
            this.mnuHelp.Index = 2;
            this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuContents,
                                                                                    this.MenuItem13,
                                                                                    this.mnuAbout});
            this.mnuHelp.Text = "Help";
            // 
            // mnuContents
            // 
            this.mnuContents.Index = 0;
            this.mnuContents.Text = "Contents";
            // 
            // MenuItem13
            // 
            this.MenuItem13.Index = 1;
            this.MenuItem13.Text = "-";
            // 
            // mnuAbout
            // 
            this.mnuAbout.Index = 2;
            this.mnuAbout.Text = "About";
            // 
            // cmdAdmin
            // 
            this.cmdAdmin.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cmdAdmin.Location = new System.Drawing.Point(132, 88);
            this.cmdAdmin.Name = "cmdAdmin";
            this.cmdAdmin.Size = new System.Drawing.Size(80, 24);
            this.cmdAdmin.TabIndex = 3;
            this.cmdAdmin.Text = "Admin Level";
            this.cmdAdmin.Click += new System.EventHandler(this.cmdAdmin_Click);
            // 
            // cmdUser
            // 
            this.cmdUser.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cmdUser.Location = new System.Drawing.Point(44, 88);
            this.cmdUser.Name = "cmdUser";
            this.cmdUser.Size = new System.Drawing.Size(80, 24);
            this.cmdUser.TabIndex = 2;
            this.cmdUser.Text = "User Level";
            this.cmdUser.Click += new System.EventHandler(this.cmdUser_Click);
            // 
            // DynamicMenu
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(256, 129);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.cmdAdmin,
                                                                          this.cmdUser});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Menu = this.mnuMain;
            this.Name = "DynamicMenu";
            this.Text = "Dynamic Menu";
            this.Load += new System.EventHandler(this.DynamicMenu_Load);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new DynamicMenu());
        }

        private void DynamicMenu_Load(object sender, System.EventArgs e)
        {
            cmdUser_Click(null,null);

        }

        private void cmdUser_Click(object sender, System.EventArgs e)
        {
            DataTable dtPermissions;

            // Get permissions for an Admin-level user.
            dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.User);

            // Update the menu with these permissions.
            SearchMenu(this.Menu, dtPermissions);

        }

        private void cmdAdmin_Click(object sender, System.EventArgs e)
        {
            DataTable dtPermissions;

            // Get permissions for an Admin-level user.
            dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.Admin);

            // Update the menu with these permissions.
            SearchMenu(this.Menu, dtPermissions);

        }

        private void SearchMenu(Menu menu, DataTable dtPermissions)
        {
            DataRow[] rowMatch;

            foreach (MenuItem mnuItem in menu.MenuItems)
            {           
                // See if this menu item has a corresponding row.
                rowMatch = dtPermissions.Select("ControlName = &#039;" + mnuItem.Text + "&#039;");

                // If it does, configure the menu item state accordingly.           
                if (rowMatch.GetLength(0) > 0)
                {
                    DBPermissions.State state;
                    state = (DBPermissions.State)int.Parse(rowMatch[0]["State"].ToString());

                    switch (state)
                    {
                        case DBPermissions.State.Hidden:
                            mnuItem.Visible = false;
                            break;
                        case DBPermissions.State.Disabled:
                            mnuItem.Enabled = false;
                            break;
                    }
                }
                else
                {
                    mnuItem.Visible = true;
                    mnuItem.Enabled = true;
                }

                // Search recursively through any submenus.
                if (mnuItem.MenuItems.Count > 0)
                {
                    SearchMenu(mnuItem, dtPermissions);
                }
            }
        }

    }
    public class DBPermissions
    {
        public enum State
        {
            Normal = 0,
            Disabled = 1,
            Hidden = 2
        }

        public enum Level
        {
            Admin,
            User
        }

        private static SqlConnection con = new SqlConnection("Data Source=localhost;"
            + "Integrated Security=SSPI;Initial Catalog=Apress;");

        public static DataTable GetPermissions(Level userLevel)
        {
            con.Open();

            // Permissions isn&#039;t actually actually a table in our data source.
            // Instead, it&#039;s a view that combines the important information
            // from all three tables using a Join query.
            string selectPermissions = "SELECT * FROM Permissions ";

            switch (userLevel)
            {
                case Level.Admin:
                    selectPermissions += "WHERE LevelName = &#039;Admin&#039;";
                    break;
                case Level.User:
                    selectPermissions += "WHERE LevelName = &#039;User&#039;";
                    break;
            }

            SqlCommand cmd = new SqlCommand(selectPermissions, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds, "Permissions");

            con.Close();

            return ds.Tables["Permissions"];
        }
    }

}
/*
-- Database Dump Wizard Ver 2.2.1 (libmssql version 2.3)
--
-- Host: localhost    Database: [Apress]
-- ---------------------------------------------------------
-- Server version   Microsoft SQL Server Version 8.0.255


-- Dumping user-defined datatypes in &#039;[Apress]&#039;


-- Table structure for table &#039;Controls&#039;
CREATE TABLE [Controls] (
[ID] int IDENTITY NOT NULL,
[ControlName] varchar(20) NOT NULL)
GO

CREATE UNIQUE CLUSTERED INDEX PK_Controls ON [Controls] (ID)
GO


-- Dumping data for table &#039;Controls&#039;
--

-- Enable identity insert
SET IDENTITY_INSERT [Controls] ON
GO

INSERT INTO [Controls] ([ID], [ControlName])
VALUES(1, &#039;New&#039;)
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(2, &#039;Save&#039;)
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(3, &#039;Manage Hardware&#039;)
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(4, &#039;Setup User Accounts&#039;)
GO

-- Disable identity insert
SET IDENTITY_INSERT [Controls] OFF
GO



-- Table structure for table &#039;Controls_Levels&#039;
CREATE TABLE [Controls_Levels] (
[ID] int IDENTITY NOT NULL,
[Control_ID] int NOT NULL,
[Level_ID] int NOT NULL,
[State] smallint)
GO

CREATE UNIQUE CLUSTERED INDEX PK_Control_Levels ON [Controls_Levels] (ID)
GO


-- Dumping data for table &#039;Controls_Levels&#039;
--

-- Enable identity insert
SET IDENTITY_INSERT [Controls_Levels] ON
GO

INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(1, 1, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(2, 2, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(3, 3, 2, 2)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(4, 4, 2, 2)
GO

-- Disable identity insert
SET IDENTITY_INSERT [Controls_Levels] OFF
GO



-- Table structure for table &#039;Levels&#039;
CREATE TABLE [Levels] (
[ID] int IDENTITY NOT NULL,
[LevelName] varchar(50))
GO

CREATE UNIQUE CLUSTERED INDEX PK_UserLevels ON [Levels] (ID)
GO


-- Dumping data for table &#039;Levels&#039;
--

-- Enable identity insert
SET IDENTITY_INSERT [Levels] ON
GO

INSERT INTO [Levels] ([ID], [LevelName])
VALUES(1, &#039;Admin&#039;)
GO
INSERT INTO [Levels] ([ID], [LevelName])
VALUES(2, &#039;User&#039;)
GO

-- Disable identity insert
SET IDENTITY_INSERT [Levels] OFF
GO


CREATE VIEW [Permissions]
AS
SELECT     Controls.ControlName, Levels.LevelName, Controls_Levels.State
FROM         Controls INNER JOIN
                      Controls_Levels ON Controls.ID = Controls_Levels.Control_ID INNER JOIN
                      Levels ON Controls_Levels.Level_ID = Levels.ID
GO


*/