Search code examples
c#.netwinformstoolstripmenustrip

How can we highlight active menu-item on clicking menu strip item?


I am working on a desktop application in C# WinForms. I have used menustrip to navigate between different panels. The problem which I am facing is I cannot highlight the active color of the menustrip icon. A pictorial description will explain better what I want to achive.

This is my menu strip

enter image description here

and on click MenuStripItem I want to achieve this

enter image description here

In short I want to the menu strip item to stay highlighted when I press Click on it just like Search and Edit in the picture and afterwards if I click on New Customers then it must be highlighted as Search & Edit


Solution

  • You can use ToolStrip instead and set items Checked property to true. To do so, you can handle ItemClicked event of ToolStrip and check items this way:

    private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        foreach (ToolStripButton item in ((ToolStrip)sender).Items)
        {
            if (item != e.ClickedItem)
                item.Checked = false;
            else
                item.Checked = true;
        }
    }
    

    This way it shows a border around checked item. If for any reason you are not satisfied with appearance, you can simply customize the appearance of checked item by creating a custom renderer and assigning it as renderer of the ToolStrip this way:

    public class MyRenderer : ToolStripProfessionalRenderer
    {
        public MyRenderer() : base(new MyColorTable())
        {
        }
    }
    
    public class MyColorTable : ProfessionalColorTable
    {
        public override Color ButtonCheckedGradientBegin
        {
            get { return ButtonPressedGradientBegin; }
        }
        public override Color ButtonCheckedGradientEnd
        {
            get { return ButtonPressedGradientEnd; }
        }
        public override Color ButtonCheckedGradientMiddle
        {
            get { return ButtonPressedGradientMiddle; }
        }
    }
    

    And assign the renderer in Load event of in constructor of your form after initialize components this way:

    toolStrip1.Renderer = new MyRenderer();
    

    This way, it shows the checked item as highlighted.