Change the BackColor of the ToolStripSeparator control

為{幸葍}努か 提交于 2019-11-28 01:33:47

The default toolstrip renderer ignores the BackColor property and uses hard-coded colors.

You can refer following link to use your own renderer to paint the separators the way you want them.

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

I see the question was asked 2 years ago, but I still can't find a simple and clear solution for this on the web. So...

I've just faced the problem today and found that it's pretty simple to solve it.

Having the same situation:

Solution:

Create a class which inherits the ToolStripSeparator class and add a method to the Paint EventHandler to draw the separator:

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);
    }
}

Then add the separator:

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);

Result:

I just pointed my separators' Paint event to this custom proc:

    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);

    }

Where the CUSTOM_COLOR_FOREGROUND is a solid/named Color, such as Color.White for example.

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

Please refer above link. I hope that helps you!

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