C#: Disappearing arrow after OnRenderSplitButtonBackground override

133 views Asked by At

I was trying to change the background of a ToolStripSplitButton using an override, but by doing that the arrow on the dropdown disappears when hovering on the button.

Code:

protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e)
{
    if (!e.Item.Selected)
    {
        base.OnRenderSplitButtonBackground(e);
    }
    else
    {
        Rectangle button = new Rectangle(0, 0, e.Item.Size.Width - 12, e.Item.Size.Height - 1);
        e.Graphics.FillRectangle(Brushes.White, button);
        e.Graphics.DrawRectangle(Pens.Olive, button);

        Rectangle dropdown = new Rectangle(e.ToolStrip.Items[0].Size.Width - 1, 0, e.Item.Size.Width - 32, e.Item.Size.Height - 1);
        e.Graphics.FillRectangle(Brushes.White, dropdown);
        e.Graphics.DrawRectangle(Pens.Olive, dropdown);
    }
}

The result looks like this:

ToolStripSplitButton

I know that OnRenderArrow exists, and I also tried to override that, but it looks like it's "overwritten" by the dropdown Rectangle in OnRenderSplitButtonBackground.

How should I fix this? Thanks in advance!

1

There are 1 answers

1
dr.null On BEST ANSWER

If you cast the base class that the e.Item property returns (the ToolStripItem) to the ToolStripSplitButton class, you will get all the relevant properties to draw the different parts of the split button.

Bounds properties such as, ButtonBounds, DropDownButtonBounds, SplitterBounds. State properties; ButtonPressed, ButtonSelected, DropDownButtonPressed, ...etc.

As for the arrow part. You need to invoke the OnRenderArrow method.

Example

protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e)
{
    if (!e.Item.Selected || e.Item.Pressed)
        base.OnRenderSplitButtonBackground(e);
    else
    {
        var sb = e.Item as ToolStripSplitButton;
        var button = sb.ButtonBounds;
        var dropdown = sb.DropDownButtonBounds;

        button.Width--;
        button.Height--;
        dropdown.Width--;
        dropdown.Height--;

        var br = sb.ButtonPressed ? Brushes.Gainsboro : Brushes.White;

        e.Graphics.FillRectangle(br, button);
        e.Graphics.DrawRectangle(Pens.Olive, button);
        e.Graphics.FillRectangle(Brushes.White, dropdown);
        e.Graphics.DrawRectangle(Pens.Olive, dropdown);

        OnRenderArrow(new ToolStripArrowRenderEventArgs(
            e.Graphics, e.Item, sb.DropDownButtonBounds, e.Item.ForeColor,
            ArrowDirection.Down));
    }
}

SOQ65328100