Search code examples
c#winformstoolstrip

ToolStrip.Background only changes button's background (C#/.NET/WinForms)


I want my ToolStrip Background to change when an Item is not saved.

To render the background of my toolstrip I use my own renderer:

    class ToolStripRenderer : ToolStripProfessionalRenderer
    {
        private MenuBarForm parent;

        public ToolStripRenderer(MenuBarForm Parent)
        {
            parent = Parent;
        }

        protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
        {
            if (parent.controlItems.Last().Unsaved)
                e.Graphics.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(e.ToolStrip.ClientRectangle, SystemColors.ControlLightLight, Color.Red, 90, true), e.AffectedBounds);
            else
                e.Graphics.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(e.ToolStrip.ClientRectangle, SystemColors.ControlLightLight, SystemColors.ControlDark, 90, true), e.AffectedBounds);
        }
    }

The first time the toolstrip renders it renders correctly with a grey to dark grey design:

CorrectToolstrip

But when the bar should become red, only the buttons which the mouse hovers over become red:

IncorrectToolstrip

I would like the whole toolstrip the be red-colored at once.

I already tried changing e.AffectedBounds to e.ToolStrip.Bounds, to no avail.


Solution

  • I Found this solution Thanks to FSDaniel comment:

    By adding Invalidate() to the end of the OnRenderToolStripBackground the toolstrip did indeed become fully red but also caused the application to go into a infinite loop. I solved this by creating an event that was triggered by changing the UnSaved property. The form that has the toolstrip then subscribed a method to this event which called toolstrip.Invalidate(). This way Invalidate() is only used when necessary.