我想知道什么时候我们应该在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);
}
Run Code Online (Sandbox Code Playgroud)
我得到stackoerflowexception,为什么?
你没有覆盖这个OnPaint()方法.你只是订阅Paint活动,所以你不应该打电话base.OnPaint().
您应该(只能)base.OnPaint()在覆盖OnPaint()表单方法时调用:
protected override OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// ... other drawing commands
}
Run Code Online (Sandbox Code Playgroud)
OnPaintWindows窗体控件上的方法实际上会引发控件Paint事件并绘制控件界面.通过OnPaint在Paint事件处理程序中调用基本表单的方法,您实际上是在告诉表单Paint一次又一次地调用处理程序,因此您将陷入无限循环,因此StackOverflowException.
当您覆盖OnPaint控件的方法时,通常应该调用基本方法,让控件自己绘制并调用订阅Paint事件的事件处理程序.如果不调用基本方法,则不会绘制某些控件方面,也不会调用任何事件处理程序.