C# 当我们重写OnPaint时,什么时候应该调用base.OnPaint()?

C# 当我们重写OnPaint时,什么时候应该调用base.OnPaint()?,c#,winforms,C#,Winforms,我想知道当我们在windows窗体程序中重写OnPaint时,什么时候应该调用base.OnPaint 我正在做的是: 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.

我想知道当我们在windows窗体程序中重写OnPaint时,什么时候应该调用base.OnPaint

我正在做的是:

  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);

        }
我得到了stackoerflowexception,为什么?

这个
base.OnPaint(e)
方法引发了
Paint
事件,所以你的
Form1\u Paint
方法在
base.OnPaint
内部被调用。这将导致无限循环,并最终导致
StackOverflowException

正确的做法是覆盖
OnPaint
方法:

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

有关更多信息,请参见此。

从上面的代码中,您没有重写OnPaint方法,您实际上是在处理绘制事件,当然,如果您尝试在处理程序中再次绘制它,您将得到一个无限循环。

您没有重写
OnPaint()
方法。您只是订阅了
Paint
事件,因此不应该调用
base.OnPaint()

当您重写表单的
OnPaint()
方法时,您应该(只能)调用
base.OnPaint()

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

    // ... other drawing commands
}
Windows窗体控件上的
OnPaint
方法实际上会引发控件的
Paint
事件,并绘制控件曲面。通过在
Paint
事件处理程序中调用基本表单的
OnPaint
方法,您实际上是在告诉表单一次又一次地调用
Paint
处理程序,因此您将陷入无限循环,从而产生
StackOverflowException


当重写控件的
OnPaint
方法时,通常应调用基本方法,以让控件自行绘制,并调用订阅
Paint
事件的事件处理程序。如果不调用基本方法,某些控件方面将不会绘制,并且不会调用任何事件处理程序。

如果希望在重写方法的“其他绘图命令”后引发绘制事件,该怎么办?@mbeckish您可以在自己的绘图后轻松调用基本方法,但是结果取决于控件的类型以及它在
OnPaint
方法中的作用。您应该意识到控件可能会在您刚刚绘制的内容上自行绘制。希望不会在
OnPaint
方法中删除背景,而是在
OnPaintBackground
方法中删除背景。