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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With