6

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?

0

3 Answers 3

8

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.

2
  • 1
    What if you want the Paint event to be raised after the overriding method's "other drawing commands"?
    – mbeckish
    Jan 18, 2013 at 18:43
  • @mbeckish You can easily call the base method after your own drawings, but the result depends on the type of control and what it does in its OnPaint method. You should be aware that the control could paints itself over what you have just drawn on it. Hopefully erasing the background will not happen in OnPaint method but in OnPaintBackground method. Jan 19, 2013 at 6:19
3

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.

2

from the code above You're not overriding the OnPaint method, you're actually handling the paint event, and, of course, if you try to paint it again inside the handler you get an infinite loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.