Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we call base.OnPaint() when we override OnPaint?

Tags:

c#

winforms

I am wondering when should we call the base.OnPaint when we override OnPaint in the windows form program?

what I am doing is:

  private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // If there is an image and it has a location, 
            // paint it when the Form is repainted.
            base.OnPaint(e);

        }

I get stackoerflowexception, why?

like image 458
user496949 Avatar asked Feb 11 '12 08:02

user496949


2 Answers

You are not overriding the OnPaint() method. You are just subscribing to Paint event, so you should not call base.OnPaint().
You should (could) only call base.OnPaint() when you override the OnPaint() method of the form:

protected override OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    // ... other drawing commands
}

The OnPaint method on Windows Forms controls actually raises the Paint event of the control and also draws the control surface. By calling the base form's OnPaint method in the Paint event handler, you actually are telling the form to call the Paint handler again and again, and so you will fall in an infinite loop, and hence the StackOverflowException.

When you override the OnPaint method of a control, usually you should call the base method, to let the control draw itself and also call the event handlers subscribed to Paint event. If you do not call the base method, some control aspects will not be drawn, and no event handler will be called.

like image 170
Mohammad Dehghan Avatar answered Sep 26 '22 00:09

Mohammad Dehghan


The base.OnPaint(e) method raises the Paint event, so your Form1_Paint method is called inside base.OnPaint. This results in an infinite loop and eventually a StackOverflowException.

The correct thing would be to override the OnPaint method:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    //custom painting here...
}

For more info, see this MSDN link.

like image 44
Smi Avatar answered Sep 26 '22 00:09

Smi