When should we call base.OnPaint () when we

I am wondering when base.OnPaint should be called, when do we override OnPaint in a Windows forms program?

What am I doing:

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 a stackoerflowexception, why?

+4
source share
3 answers

You do not override the OnPaint() method. You just subscribe to the Paint event, so you shouldn't call base.OnPaint() .
You should (could) call base.OnPaint() only when overriding the OnPaint() method of the form:

 protected override OnPaint(PaintEventArgs e) { base.OnPaint(e); // ... other drawing commands } 

The OnPaint method for Windows Forms controls actually fires the Paint event of the control and also draws the control surface. By calling the base OnPaint method in the Paint event handler, you really tell the form to call the Paint handler again and again, and so you will end up in an infinite loop, and therefore a StackOverflowException .

When you override the OnPaint method of a control, you usually need to call the base method so that the control itself executes and also calls event handlers that subscribe to the Paint event. If you do not call the base method, some aspects of the control will not be drawn, and the event handler will not be called.

+6
source

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

It would be more correct to override the OnPaint method:

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

See the MSDN link for more information.

+3
source

from the code above. You do not override the OnPaint method, you actually handle the drawing event, and, of course, if you try to draw it again inside the handler, you get an infinite loop.

+2
source

Source: https://habr.com/ru/post/1395891/


All Articles