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?
You are not overriding the
OnPaint()method. You are just subscribing toPaintevent, so you should not callbase.OnPaint().You should (could) only call
base.OnPaint()when you override theOnPaint()method of the form:The
OnPaintmethod on Windows Forms controls actually raises thePaintevent of the control and also draws the control surface. By calling the base form’sOnPaintmethod in thePaintevent handler, you actually are telling the form to call thePainthandler again and again, and so you will fall in an infinite loop, and hence theStackOverflowException.When you override the
OnPaintmethod of a control, usually you should call the base method, to let the control draw itself and also call the event handlers subscribed toPaintevent. If you do not call the base method, some control aspects will not be drawn, and no event handler will be called.