1

I have a ContextMenuStrip that has 4 items. One of the items has a submenu with another 4 items, o which one is a separator. I changed the back color for all items but the separator's backcolor does not change

Why and how change it?

Thispic

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

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

Having the same situation:

enter image description here

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:

enter image description here

Szabolcs Antal
  • 877
  • 4
  • 15
  • 27