是否可以更改 ToolStripSeparator 控件的背景颜色?设计器中有一个 BackColor 属性,但似乎没有使用 - 颜色始终为白色。
问问题
4998 次
3 回答
5
我看到这个问题是 2 年前提出的,但我仍然无法在网上找到一个简单而清晰的解决方案。所以...
我今天刚遇到这个问题,发现解决它很简单。
有同样的情况:
解决方案:
创建一个继承该类的ToolStripSeparator
类并向 中添加一个方法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);
结果:
于 2015-06-27T21:38:06.563 回答
5
我只是将分隔符的 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。
于 2016-07-16T03:19:29.003 回答
3
默认toolstrip
渲染器忽略 BackColor 属性并使用硬编码颜色。
您可以参考以下链接以使用您自己的渲染器以您想要的方式绘制分隔符。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
toolStrip1.Renderer = new MyRenderer();
}
private class MyRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
if ((e.Item as ToolStripSeparator) == null)
{
base.OnRenderSeparator(e);
return;
}
Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size);
bounds.Y += 3;
bounds.Height = Math.Max(0, bounds.Height - 6);
if (bounds.Height >= 4)
bounds.Inflate(0, -2);
int x = bounds.Width / 2;
using(Pen pen = new Pen(Color.DarkBlue))
e.Graphics.DrawLine(pen, x, bounds.Top, x, bounds.Bottom - 1);
using (Pen pen = new Pen(Color.Blue))
e.Graphics.DrawLine(pen, x + 1, bounds.Top + 1, x + 1, bounds.Bottom);
}
}
}
资料来源:http ://social.msdn.microsoft.com/forums/en-US/winforms/thread/6cceab5b-7e06-40cf-82da-56cdcc57eb5d
于 2013-04-10T12:54:42.410 回答