Search code examples
c#.netwinformsgraphics

Why doesn't Graphics.Clear appear to work properly in my custom Windows forms control?


My understanding of how you should draw a custom Windows forms control is to first call Graphics.Clear to refresh the control's background, then draw whatever you want on top of that. As such, I have the following code for the custom control I'm developing:

internal class PictureSizeCropBox : Control {
    protected override void OnPaint(PaintEventArgs ea) {
        ea.Graphics.Clear(Color.Green);

        Pen redPen = new(Color.Red, 1);

        ea.Graphics.DrawRectangle(redPen, new Rectangle(0, 0, Width - 1, Height - 1));
    }
}

However, when I put that in a Panel and my code resizes the control (and panel) upon window resize, I get this graphical effect when the window is made larger:

Graphical effect of control when resized larger

What is Graphics.Clear doing? It is drawing a green background initially but weirdly, it's not actually clearing the old stuff rendered by the control. What is the correct way to draw Windows forms controls so they correctly redraw upon resize, clearing the old rendering? Do I need to just draw a filled rectangle for the background and if so, what is the point in Graphics.Clear and when should it be used?


Solution

  • Apparently, you need to explicitly invalidate your control on resize:

        protected override void OnResize(EventArgs ea) {
            base.OnResize(ea);
            Invalidate();
        }
    

    Adding this fixes the problem.