Q:

How to keep graphics when resizing C# form

I am working on a program where I need to draw rectangle graphics onto the form itself, when I click the form. I created code to do this (below), but when I resize the form the rectangles are deleted.
How do I retain the drawn rectangles when the form is resized?  
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    Graphics g = this.CreateGraphics();
    Pen Haitham = new Pen(Color.Silver, 2);
    g.FillRectangle(Haitham.Brush, new Rectangle(e.X, e.Y, 50, 50));
}

A:

You could do this instead:
    private List<Point> _points = new List<Point>();

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        foreach(Point point in _points)
        {
            using (Pen Haitham = new Pen(Color.Silver, 2))
            {
                e.Graphics.FillRectangle(Haitham.Brush, new Rectangle(point.X, point.Y, 50, 50));
            }
        }
    }

    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        _points.Add(new Point(e.X, e.Y));
        Invalidate(); // could be optimized to invalidate only the future rectangle draw
    }

In Windows with Winforms (or native Windows), you supposed to override OnPaint and do almost all your paint logic there.
Note with WPF, it would be different, you would compose a scene adding elements to it (here you would add a Rectangle shape to a Canvas for example).

