在子菜单中更改ToolstripSeparator的背景颜色?

时间:2014-04-14 10:22:01

标签: c#

我有一个ContextMenuStrip,有4个项目。其中一个项目有一个子菜单,另外有4个项目,其中一个是分隔符。我更改了所有项目的背景颜色,但分隔符的背景颜色没有改变

为什么以及如何改变它?

Thispic

1 个答案:

答案 0 :(得分:1)

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

具有相同的情况:

enter image description here

<强>解决方案:

创建一个继承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);

<强>结果:

enter image description here