arpit1611 arpit1611 - 1 year ago 289
C# Question

Use different Highlight color for different ToolStripMenuItems

There is one ToolStripMenuItem object which is containing other 3 ToolStripMenuItems on dropdown. I want use different hightlight colors on MouseHover of different ToolStripMenuItems. Say, For Yes - Green. For No - Red. For MayBe - Blue. The color of highlight should get change accordingly as i move among different items. Please help.

P.S. - MouseEnter, MouseLeave, MouseHover events aren't working because they work on ToolStripMenuItems and it is the case of Highlighter.

Answer Source

When you are using a ToolStripProfessionalRenderer, changing back color doesn't change highlight color. Also while your tool strip uses a single renderer, since the renderer uses MenuItemSelectedColor property of ProfessionalColorTable of renderer, it can't render highlight color based on a condition.

You can change renderer of ToolStrip dynamically and set it's renderer to a renderer which draws highlight in your desired color.

enter image description here

Here are the steps which I used:

(1) Set the RenderMode of your ToolStrip to ManagerRenderMode:

this.toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode;

(2) Create a custom color table which you can pass MenuItemSelectedColor to it:

public class MyColorTable : ProfessionalColorTable
    private Color menuItemSelectedColor;
    public MyColorTable(Color color): base()
        menuItemSelectedColor = color;
    public override Color MenuItemSelected
        get { return menuItemSelectedColor; }

(3) Define renderers which you need at form level:

ToolStripProfessionalRenderer r = 
    new ToolStripProfessionalRenderer(new MyColorTable(Color.Red));
ToolStripProfessionalRenderer g = 
    new ToolStripProfessionalRenderer(new MyColorTable(Color.Green));
ToolStripProfessionalRenderer b = 
    new ToolStripProfessionalRenderer(new MyColorTable(Color.Blue));

(4) Handle MouseEnter and MouseLeave event for all your menu items which you want to use custom renderer and assign this handlers to all of them:

private void menuItem_MouseEnter(object sender, EventArgs e)
    var item = (ToolStripMenuItem)sender;
    if (item.Text == "Yes")
        ToolStripManager.Renderer = g;
    else if (item.Text == "No")
        ToolStripManager.Renderer = r;
    else if (item.Text == "MayBe")
        ToolStripManager.Renderer = b;
        ToolStripManager.Renderer = null; // or use your default renderer

private void menuItem_MouseLeave(object sender, EventArgs e)
    ToolStripManager.Renderer = null; // or use your default renderer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download