Search code examples
c#visual-studio-2008toolstripmenu

Customize ToolStripMenuItems in c#


I need to customize the ToolStripMenuItems in my application. Each ToolStripMenuItem that open a submenu has a black arrow near the text. I want to change some colors (MenuItemSelected, MenuItemBorder, MenuItemSelectedGradientBegin, ...) and the color of this arrow too. I've created a class MyColor to solve the first problem

public class MyColorTable : ProfessionalColorTable
{
  public override Color MenuItemSelected
  {
    get { return Color.Silver; }
  }

  public override Color MenuItemBorder
  {
    get { return Color.WhiteSmoke; }
  }

  public override Color MenuItemSelectedGradientBegin
  {
    get { return Color.FromArgb(60, 60, 60); }
  } 
}

and another class to change the color of the arrows

public class CustomToolStripRenderer : ToolStripProfessionalRenderer
{
  private readonly ToolStripProfessionalRenderer _toolStripRenderer;

  public CustomToolStripRenderer(ToolStripProfessionalRenderer toolStripRenderer)
  {
    _toolStripRenderer = toolStripRenderer;
  }

  protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
  {
   var tsMenuItem = e.Item as ToolStripMenuItem;
   if (tsMenuItem != null)
     e.ArrowColor = Color.White;
   base.OnRenderArrow(e);
  }

  public void Render()
  {
   _toolStripRenderer.RoundedEdges = false;
   ToolStripManager.Renderer = this;
   //ToolStripManager.Renderer = _toolStripRenderer;
  }
}

When I call the Render() method

    CustomToolStripRenderer customRenderer = new CustomToolStripRenderer(new ToolStripProfessionalRenderer(new MyColorTable()));

    customRenderer.Render();

I obtain that the arrows become white but I lose the first changes because of this line

 ToolStripManager.Renderer = this;

I'm not able to find an easy solution to solve this problem due to the static class ToolStripManager


Solution

  • Hard to make sense of the code, you definitely need to get rid of that _toolStripRenderer variable. I would write:

        public class CustomToolStripRenderer : ToolStripProfessionalRenderer {
            public CustomToolStripRenderer() : base(new MyColorTable()) {
                this.RoundEdges = true;
            }
            protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) {
                // etc..
            }
        } 
    

    Then in the form constructor:

        public Form1() {
            InitializeComponent();
            ToolStripManager.Renderer = new CustomToolStripRenderer();
        }
    

    Works fine.