Click here to Skip to main content
15,879,535 members
Articles / Multimedia / GDI+

Cool Vista-style Menu

Rate me:
Please Sign up or sign in to vote.
4.92/5 (80 votes)
3 Jan 2009CPOL3 min read 154.4K   9.3K   266   58
Cool Vista style menu in your .NET applications
Vista menu control

Introduction

This is the second release of this control, so my previous article was a bit poor, I decided to update it too. I based the development of this control on Vista start menu, but as you can see in the image above, it can be easily customized to support other styles, themes, etc. See demo project for more details (mac style menus, applying themes at runtime, etc.).

Using the Code

Using this control is extremely easy. Just add it to your toolbox, then drag & drop on your form.

Image 2

Next, populate the menu control, adding menu items. There are several overloaded methods you can use to achieve this:

  • C#
    public VistaMenuItem Add(string sText);
  • C#
    public VistaMenuItem Add(string sText, string sDescription);
  • C#
    public VistaMenuItem Add(string sText, string sDescription, Image img);
  • C#
    public VistaMenuItem Add(string sText, Image img);
  • C#
    public void Add(VistaMenuItem btn);

So, if you want rich menu items, you should use the third method. Here is a simple code to add some items:

C#
for(int idx = 0; idx < 5; idx++)
   vmcMenu.MenuItems.Add(
           "Item " + idx,
       "Description " + idx,
            img
    );

Structure

Image 3

The image below shows different elements of a menu control. Menu items are rich-rendered, that means, they have an image representation, caption to identify them, and a short description. Every menu item is limited by a separator. They can be flat, 3D, and in this release of a control, you can also specify not to render them at all. This feature will be presented later on. With a menu sidebar you can group different menus, using distinct name, and also provide an icon that will be rendered next to sidebar caption.

Image 4

Menu panel is rendered using gradient colors as shown in the image.
The control implements a lot of properties related to menu's appearance, like start and end gradient colors, inner/ outer border colors, sidebar gradient colors:

  • C#
    public Color MenuStartColor 
  • C#
    public Color MenuEndColor 
  • C#
    public Color MenuInnerBorderColor 
  • C#
    public Color MenuOuterBorderColor 
  • C#
    public Color SideBarStartGradient 
  • C#
    public Color SideBarEndGradient 

Vista menu control is also able to render background image. You can set the image alignment, defined by ContentAlignment enumeration, and then DrawBackImage is invoked to draw the image.

C#
private void DrawBackImage(
           Graphics gfx,
           Rectangle rc
           )
       {
           if (m_bmpBackImage != null)
           {
               int lW =  m_bmpBackImage.Width;
               int lH = m_bmpBackImage.Height;
               Rectangle rcImage = new Rectangle(
                   0,
                   0,
                   lW,
                   lH
                   );

               switch (m_ImageAlign)
               {
                   case ContentAlignment.BottomCenter:
                       rcImage.X = rc.Width / 2 - lW / 2;
                       rcImage.Y = rc.Height - lH - 2;
                       break;
                   case ContentAlignment.BottomLeft:
                       rcImage.X = rc.Left + 2;
                       rcImage.Y = rc.Height - lH - 2;
                       break;
                   case ContentAlignment.BottomRight:
                       rcImage.X = rc.Right - lW -  2;
                       rcImage.Y = rc.Height - lH - 2;
                       break;
                   case ContentAlignment.MiddleCenter:
                       rcImage.X = rc.Width / 2 - lW / 2;
                       rcImage.Y = rc.Height / 2 - lH / 2;
                       break;
                   case ContentAlignment.MiddleLeft:
                       rcImage.X = rc.Left + 2;
                       rcImage.Y = rc.Height / 2 - lH / 2;
                       break;
                   case ContentAlignment.MiddleRight:
                       rcImage.X = rc.Right - lW - 2;
                       rcImage.Y = rc.Height / 2 - lH / 2;
                       break;
                   case ContentAlignment.TopCenter:
                       rcImage.X = rc.Width / 2 - lW / 2;
                       rcImage.Y = rc.Top + 2;
                       break;
                   case ContentAlignment.TopLeft:
                       rcImage.X = rc.Left + 2;
                       rcImage.Y = rc.Top + 2;
                       break;
                   case ContentAlignment.TopRight:
                       rcImage.X = rc.Right - lW - 2;
                       rcImage.Y = rc.Top + 2;
                       break;
               }

               gfx.DrawImage(
                   m_bmpBackImage,
                   rcImage
               );
           }
       }

Image 5

Implementation

Image 6

DrawMenuItems is a core method of a menu control.

C#
private void DrawMenuItems(
             Graphics gfx,
             Rectangle rc,
             float r
            )
        {
            Rectangle rcItem = new Rectangle();
            bool bVertical = (m_eMenuOrientation == VistaMenuOrientation.Vertical) 
				? true : false;

            if (bVertical)
            {
                rcItem.X = 5;
                rcItem.Y = 4;
                rcItem.Width = rc.Width - 10;
                rcItem.Height = m_lItemHeight;
            }
            else
            {
                rcItem.X = 5;
                rcItem.Y = 4;
                rcItem.Width = m_lItemWidth;
                rcItem.Height = rc.Height - 7;
            }
            if (m_bDrawBar){

               rcItem.X = m_lBarWidth;
               rcItem.Width -= m_lBarWidth - 5;
            }

            Rectangle rcUpRect = rcItem;
            Rectangle rcDownRect = rcItem;

            rcUpRect.Height /= 2;
            rcDownRect.Height /= 2;
            rcDownRect.Y = rcUpRect.Height + 3;

            if (items == null || items.Count == 0)
                return;

            gfx.SmoothingMode = SmoothingMode.HighQuality;
            gfx.CompositingQuality = CompositingQuality.HighQuality;
            gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

            foreach (VistaMenuItem item in items) {

                #region Draw selection / checked state
                try
                {
                    item.Left = rcItem.X;
                    item.Top = rcItem.Y;
                    Rectangle rcItemInner = rcItem;
                    if (item.Checked)
                    {
                        if (item.Hovering)
                        {
                            FillMenuItem(
                                gfx,
                                rcUpRect,
                                rcDownRect,
                                item.CheckedStartColor,
                                item.CheckedEndColor,
                                item.CheckedStartColorStart,
                                item.CheckedEndColorEnd,
                                r
                            );
                            DrawItemBorder(
                                   gfx,
                                   rcItemInner,
                                   item.MouseDown,
                                   item.InnerBorder,
                                   item.OuterBorder,
                                   r
                            );
                        }
                        else
                        {
                            FillMenuItem(
                                gfx,
                                rcUpRect,
                                rcDownRect,
                                item.CheckedStartColor,
                                item.CheckedEndColor,
                                item.CheckedStartColorStart,
                                item.CheckedEndColorEnd,
                                r
                            );
                            DrawItemBorder(
                                    gfx,
                                    rcItemInner,
                                    item.MouseDown,
                                    item.InnerBorder,
                                    item.OuterBorder,
                                    r
                             );
                        }
                    }
                    else
                    {
                        if (item.Hovering)
                        {
                            if (!item.Disabled)
                            {

                                FillMenuItem(
                                    gfx,
                                    rcUpRect,
                                    rcDownRect,
                                    item.SelectionStartColor,
                                    item.SelectionEndColor,
                                    item.SelectionStartColorStart,
                                    item.SelectionEndColorEnd,
                                    r
                                );
                                DrawItemBorder(
                                    gfx,
                                    rcItemInner,
                                    item.MouseDown,
                                    item.InnerBorder,
                                    item.OuterBorder,
                                    r
                                );
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(
                        e.ToString()
                    );
                }
                #endregion

                #region Draw icons

                if (item.Image != null)
                {
                    Rectangle rcIcon = new Rectangle();
                    rcIcon.X = rcItem.X + 2;
                    rcIcon.Y = rcItem.Bottom - item.Image.Height;
                    rcIcon.Width = item.Image.Width;
                    rcIcon.Height = item.Image.Height;

                    if (item.Disabled)
                    {
                        ControlPaint.DrawImageDisabled(
                            gfx,
                            item.Image,
                            rcIcon.X,
                            rcIcon.Y,
                            Color.Transparent);
                    }
                    else
                    {
                        gfx.DrawImage(
                            item.Image,
                            rcIcon
                        );
                    }
                }

                #endregion

                #region Draw separators
                if (m_bSeparators)
                {
                    Point pStart = new Point();
                    Point pEnd = new Point();
                    if (bVertical)
                    {
                        pStart = new Point(rcItem.Left + 3, rcItem.Bottom);
                        pEnd = new Point(rcItem.Right - 3, rcItem.Bottom);
                    }
                    else
                    {
                        pStart = new Point(rcItem.Right, rcItem.Top);
                        pEnd = new Point(rcItem.Right, rcItem.Bottom);
                    }
                    using (Pen pInner = new Pen(m_clrInnerBorder),
                                    pOuter = new Pen(m_clrOuterBorder))
                    {

                        if (!m_bFlatSeparators)
                        {
                            // don't draw separator for last item:
                            if (items.IndexOf(item) < items.Count - 1)
                            {
                                if (bVertical)
                                {

                                    gfx.DrawLine(pOuter, pStart, pEnd);
                                    pStart.Y += 1; pEnd.Y += 1;
                                    gfx.DrawLine(pInner, pStart, pEnd);
                                }
                                else
                                {
                                    gfx.DrawLine(pOuter, pStart, pEnd);
                                    pStart.X += 1; pEnd.X += 1;
                                    gfx.DrawLine(pInner, pStart, pEnd);
                                }
                            }
                        }
                        else
                        {
                            Pen pFlat = new Pen(m_clrFlatSeparators);
                            // don't draw separator for last item:
                            pStart.Y += 1; pEnd.Y += 1;
                            if (items.IndexOf(item) < items.Count - 1)
                                gfx.DrawLine(pFlat, pStart, pEnd);
                            // clean up:
                            pFlat.Dispose();
                        }

                    }
                }
                #endregion

                #region Draw item's text
                StringFormat sf = new StringFormat();
                StringFormat sfUpper = new StringFormat();
                sfUpper.Trimming = StringTrimming.EllipsisCharacter;
                sfUpper.FormatFlags = StringFormatFlags.LineLimit;
                sf.Trimming = StringTrimming.EllipsisCharacter;
                sf.FormatFlags = StringFormatFlags.LineLimit;

                Rectangle rcCaption = rcUpRect;
                Rectangle rcContent = rcDownRect;

                if (item.Image != null)
                {
                    sfUpper.Alignment = StringAlignment.Near;
                    sfUpper.LineAlignment = StringAlignment.Near;
                    sfUpper.LineAlignment = StringAlignment.Center;
                    sf.Alignment = StringAlignment.Near;

                    Rectangle rcImage = new Rectangle(
                          rcItem.X + 2,
                          rcItem.Y,
                          item.Image.Width,
                          item.Image.Height);

                    rcCaption.X = rcImage.Right + 2;
                    rcContent.X = rcImage.Right + 4;
                    rcCaption.Width -= rcImage.Width;
                    rcContent.Width -= rcImage.Width + 4;
                }
                else
                {
                    sfUpper.Alignment = StringAlignment.Center;
                    sfUpper.LineAlignment = StringAlignment.Near;
                    sfUpper.LineAlignment = StringAlignment.Center;
                    sf.Alignment = StringAlignment.Center;
                }
                // draw text for item's caption / description:
                SolidBrush sbCaption = new SolidBrush(Color.Empty);
                SolidBrush sbContent = new SolidBrush(Color.Empty);
                if (item.Checked)
                {
                    sbCaption.Color = item.CheckedCaptionColor;
                    sbContent.Color = item.CheckedContentColor;
                }
                else
                {
                    sbCaption.Color = item.CaptionColor;
                    sbContent.Color = item.ContentColor;
                }

                gfx.DrawString(item.Text, item.CaptionFont, sbCaption, 
				rcCaption, sfUpper);
                gfx.DrawString(item.Description, item.ContentFont, 
				sbContent, rcContent, sf);

                sfUpper.Dispose();
                sf.Dispose();
                sbCaption.Dispose();
                sbCaption.Dispose();
                #endregion

                #region Update positions
                if (bVertical)
                {
                    rcUpRect.Y += rcItem.Height + 2;
                    rcDownRect.Y += rcItem.Height + 2;
                    rcItem.Y += rcItem.Height + 2;
                }
                else
                {
                    rcUpRect.X += rcItem.Width + 2;
                    rcDownRect.X += rcItem.Width + 2;
                    rcItem.X += rcItem.Width + 2;

                }
                #endregion
            }
        }

It controls the rendering process of menu items, depending on item's state (disabled, hovering, checked). Also, it specifies how item caption, description, image and separators are rendered according to the orientation of a menu.

Each of the menu items is represented by VistaMenuItem class. As shown in the class diagram, there are a huge number of properties to customize an item's appearance. VistaMenuItems is a class extended from CollectionBase and it holds all menu items, and controls the addition / deletion. This way, we can easily perform hittest operations, when searching the hovering item, or detecting mouse clicks over target menu item.
Other important methods, related to menu's functionality are HitTestItem, and CalcMenuSize.

C#
    private int HitTestItem(
        int x,
        int y
        )
    {
        int code = -1;
        VistaMenuItem item = null;

        if ((x > m_lBarWidth) && (x <= this.ClientRectangle.Width))
        {
            if ((y >= 2) && (y <= this.ClientRectangle.Height))
            {

                for (int idx = 0; idx < items.Count; idx++)
                {
                    item = items[idx];
                    if (y >= item.Top)
                    {
                        if (y < item.Top + m_lItemHeight)
                        {
                            code = idx;
                            break;
                        }
                    }
                }
            }
        }
        if (code == -1)
        {
            // cursor inside side bar:
            for (int i = 0; i < items.Count; i++)
            {
                // unhover any hovering item:
                items[i].Hovering = false;
                Cursor = Cursors.Default;
                Invalidate();
            }
        }
        return code;
    }

    public void CalcMenuSize()
    {
        if (!this.DesignMode){

            int lHeight = (items.Count  ) * (m_lItemHeight + 3 ) + 1 ;
            int lWidth = (items.Count) * (m_lItemWidth + 4) + 1;
            if (m_eMenuOrientation == VistaMenuOrientation.Vertical)
            {
                this.MaximumSize = new Size(this.Width, lHeight);
                this.Size = new Size(this.Width, lHeight);
            }
            else
            {

                this.MinimumSize = new Size(this.m_lItemWidth, this.m_lItemHeight);
                this.MaximumSize = new Size(lWidth, this.m_lItemHeight + 5);
                this.Size = new Size(lWidth, this.m_lItemHeight + 5);
            }
            Invalidate();
        }
    }
}

The first of them is used to find an hovering item when the sidebar is rendered. It first checks if mouse is inside the menu area, excluding sidebar rectangle width. If condition evaluates to true, then we iterate through items collection, and find the correct item index. The second one dynamically adjusts menu height or width, depending on menu's orientation.

New Features

Image 7

One of the new cool features in this update is the ability to show menu horizontally. This feature is controlled by MenuOrientation property. I found this feature specially interesting to use in the main application's window where you can introduce parts of your application. For example, Nero StartSmart Essentials. Note that, when menu is shown horizontally, sidebar can't be rendered.

Another useful feature implemented, is checked state. When item is checked, you can specify , item's gradient colors, and also caption / description font color. To activate this feature you should set CheckOnClick feature to true.

Image 8

You can programmatically get / select menu item using SelectedItem property.

C#
public int SelectedItem
{
     get
     {
         int idx = -1;
         for (int i = 0; i < items.Count; i++) {
               if (items[i].Checked)
                    idx = items.IndexOf(items[i]);
         }
         return idx;
      }
      set
      {
         if (value < 0 || value > items.Count)
            return;

         for (int i = 0; i < items.Count; i++){
              if (items[value].Disabled)
                  return;

              items[value].Checked = true;
         }
         Invalidate();
      }
}	

The last feature provided in this release is the possibility to disable separators rendering.

Image 9

Demo Project

Click to enlarge image

Please make sure that you copy Visitor TT2 BRK font to your Fonts folder, before running the sample project.

History

  • 7th November, 2008: Initial version
  • 21th November, 2008: Repainting issue fixed
  • 25th November, 2008: Added new features
  • 28th December, 2008: Second release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Spain Spain
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
BugProblem Pin
User 1192862114-Apr-17 6:04
User 1192862114-Apr-17 6:04 
Questioncan i use scrolling Pin
Atif BOUZAGLAOUI19-Jun-15 18:34
Atif BOUZAGLAOUI19-Jun-15 18:34 
GeneralVery good. My vote 5 Pin
N. Henrik Lauridsen5-May-15 3:01
N. Henrik Lauridsen5-May-15 3:01 
QuestionMake availability of SUBMENU Pin
shriram201216-Apr-12 4:07
shriram201216-Apr-12 4:07 
GeneralMy vote of 5 Pin
RAJI @Codeproject28-Oct-11 20:53
RAJI @Codeproject28-Oct-11 20:53 
GeneralMy vote of 5 Pin
FernandoUY20-Dec-10 4:27
professionalFernandoUY20-Dec-10 4:27 
GeneralReally nice and great Pin
blackeyes24-Sep-10 11:48
blackeyes24-Sep-10 11:48 
GeneralThanks Pin
Francisco Soto20-Jul-10 23:08
Francisco Soto20-Jul-10 23:08 
GeneralMy vote of 5 Pin
Francisco Soto20-Jul-10 23:06
Francisco Soto20-Jul-10 23:06 
GeneralGreat Work Pin
asmaqureshi821116-Jun-10 21:18
asmaqureshi821116-Jun-10 21:18 
GeneralRe: Great Work Pin
Nedim Sabic18-Jun-10 7:29
Nedim Sabic18-Jun-10 7:29 
GeneralI like it Pin
Yves12-May-10 11:21
Yves12-May-10 11:21 
Generalthanks for sharing, but Pin
Athar.AliKhan23-Feb-10 1:28
Athar.AliKhan23-Feb-10 1:28 
GeneralNice one, thanks for sharing, but Pin
Aristocratk20-Feb-10 6:37
Aristocratk20-Feb-10 6:37 
GeneralRe: Nice one, thanks for sharing, but Pin
Nedim Sabic22-Feb-10 23:51
Nedim Sabic22-Feb-10 23:51 
Generalkeyboard keys Pin
Aristocratk20-Feb-10 2:27
Aristocratk20-Feb-10 2:27 
GeneralTruly Briliant Pin
Allan Gaunt13-Feb-10 11:23
Allan Gaunt13-Feb-10 11:23 
GeneralRe: Truly Briliant Pin
Nedim Sabic16-Feb-10 5:05
Nedim Sabic16-Feb-10 5:05 
GeneralVery Nice Pin
AmirNapster17-Dec-09 6:09
AmirNapster17-Dec-09 6:09 
GeneralBravo Majstore! Pin
Amer Gerzic7-Apr-09 6:51
Amer Gerzic7-Apr-09 6:51 
GeneralContext menu Pin
limit200619-Mar-09 17:53
limit200619-Mar-09 17:53 
GeneralScrollBar Pin
buzzness00710-Feb-09 11:08
buzzness00710-Feb-09 11:08 
Generaldraw icon's item position Pin
Edward11119-Jan-09 15:26
Edward11119-Jan-09 15:26 
Questionitems at design time? Pin
Edward11119-Jan-09 15:20
Edward11119-Jan-09 15:20 
i use vs2008 and at design time I doesn't see any items, just plain color panel, does this control works at design time?, if so, do you know what is my problem about it ?

thanks in advance for your help,
AnswerRe: items at design time? Pin
Nedim Sabic19-Jan-09 21:22
Nedim Sabic19-Jan-09 21:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.