Search code examples
c#system.drawingpaintevent

When are C# Draw/Fill functions called? How can they be invoked from a separate class?


I'm not sure of how the Paint form lifecycle works, when is the Form1_Paint function called? How can I control when it's called?

I know I can call Draw a Circle using the C# Drawing library like so:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.FillEllipse(Brushes.Red, new Rectangle(1, 1, 1, 1));
}

If I define an object like so:

class myCircleObject
{
    int x, y, radius;

    public myCircleObject(int x_val, int y_val, int r)
    {
        x = x_val;
        y = y_val;
        radius = r;
    }

    public void Draw()
    {
        System.Drawing.Rectangle r = new System.Drawing.Rectangle(x, y, radius, radius);
        //Draw Circle here
    }
}

or if I can't do that how can I call the Form1_Paint function as opposed to it just running immediately at run time.


Solution

  • There are two ways:

    • The typical way is to paint asynchronously. Call Invalidate on whatever form/control has your custom drawing logic. The framework will raise the Paint event method at the appropriate time.
    • A more forceful (non-recommended) way is to paint synchronously. Call Refresh on your form/control, which will cause it to raise Paint immediately.

    For example (this is not complete, but it illustrates the concept):

    public class Form1
    {
        private MyCircle _circle;
    
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
           _circle.Draw(e); // this line causes the Circle object to draw itself on Form1's surface
        }
    
        public void MoveTheCircle(int xOffset, int yOffset)
        {
            _circle.X += xOffset; // make some changes that cause the circle to be rendered differently
            _circle.Y += yOffset;
            this.Invalidate(); // this line tells Form1 to repaint itself whenever it can
        }
    }