更改ToolStripSeparator控件的BackColor

是否可以更改ToolStripSeparator控件的BackColor? 设计器中有一个BackColor属性,但似乎没有使用它 – 颜色总是白色。

默认toolstrip渲染器忽略BackColor属性并使用硬编码颜色。

您可以参考以下链接以使用您自己的渲染器以您希望的方式绘制分隔符。

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/6cceab5b-7e06-40cf-82da-56cdcc57eb5d

我看到2年前问过这个问题,但我仍然无法在网上找到一个简单明了的解决方案。 所以…

我今天刚遇到问题,发现解决它很简单。

有相同的情况:

在此处输入图像描述

解:

创建一个inheritanceToolStripSeparator类的类,并向Paint EventHandler添加一个方法来绘制分隔符:

 public class ExtendedToolStripSeparator : ToolStripSeparator { public ExtendedToolStripSeparator() { this.Paint += ExtendedToolStripSeparator_Paint; } private void ExtendedToolStripSeparator_Paint(object sender, PaintEventArgs e) { // Get the separator's width and height. ToolStripSeparator toolStripSeparator = (ToolStripSeparator)sender; int width = toolStripSeparator.Width; int height = toolStripSeparator.Height; // Choose the colors for drawing. // I've used Color.White as the foreColor. Color foreColor = Color.FromName(Utilities.Constants.ControlsRelatedConstants.standardForeColorName); // Color.Teal as the backColor. Color backColor = Color.FromName(Utilities.Constants.ControlsRelatedConstants.standardBackColorName); // Fill the background. e.Graphics.FillRectangle(new SolidBrush(backColor), 0, 0, width, height); // Draw the line. e.Graphics.DrawLine(new Pen(foreColor), 4, height / 2, width - 4, height / 2); } } 

然后添加分隔符:

 ToolStripSeparator toolStripSeparator = new ExtendedToolStripSeparator(); this.DropDownItems.Add(newGameToolStripMenuItem); this.DropDownItems.Add(addPlayerToolStripMenuItem); this.DropDownItems.Add(viewResultsToolStripMenuItem); // Add the separator here. this.DropDownItems.Add(toolStripSeparator); this.DropDownItems.Add(exitToolStripMenuItem); 

结果:

在此处输入图像描述

我只是将我的分隔符’Paint事件指向了这个自定义过程:

  private void mnuToolStripSeparator_Custom_Paint (Object sender, PaintEventArgs e) { ToolStripSeparator sep = (ToolStripSeparator)sender; e.Graphics.FillRectangle(new SolidBrush(CUSTOM_COLOR_BACKGROUND), 0, 0, sep.Width, sep.Height); e.Graphics.DrawLine(new Pen(CUSTOM_COLOR_FOREGROUND), 30, sep.Height / 2, sep.Width - 4, sep.Height / 2); } 

其中CUSTOM_COLOR_FOREGROUND是实体/命名颜色,例如Color.White。

http://www.c-sharpcorner.com/uploadfile/mahesh/toolstrip-in-C-Sharp/

请参考以上链接。 我希望能帮到你!