Customize ToolStripMenuItems in c#

北城余情 提交于 2019-12-11 08:15:34

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26614398/customize-toolstripmenuitems-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!