有趣的C#中OnPaint事件
(2011-04-06 17:21:14)
标签:
杂谈 |
分类: .NET |
先看下边的两段程序:
程序段1:
public
static void Main()
{
Application.Run(new
HelloWorld());
}
public
HelloWorld()
{
Text = "HelloWorld";
BackColor = Color.Black;
}
protected override void OnPaint(PaintEventArgs
e)
{
base.OnPaint(e);
Graphics grfx =
e.Graphics;
grfx.Clear(Color.Blue);
grfx.DrawString("Hello World
!!", this.Font, Brushes.Red, 0, 0);
}
public
new static void Main()
{
Form form = new
HelloWorld();
form.Text = "Inherit " +
form.Text;
form.Paint += new
PaintEventHandler(MyPaintHander);
Application.Run(form);
}
static
void MyPaintHander(object objSender, PaintEventArgs pea)
{
Form from =
(Form)objSender;
Graphics grfx =
pea.Graphics;
grfx.DrawString("Hello World
from InhertHello",from.Font,Brushes.Black,0,200);
}
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
class HelloWorld : Form
{
}
程序段2:
using System;
using System.Windows;
using System.Drawing;
using System.Windows.Forms;
class InheritHelloWorld
{
}
这段程序的最终现实结果为:hello World Froms;
Control类中的Onpaint方法负责安装已经加载的MyPaintHander方法,但是HelloWorld类中覆盖了Onpaint这个OPaint这个方法,所以哪项作业并没有完成。这就是.Net文档在建议在覆盖一个on开头的受保护的方法时,应该向这样调用基类中的方法:base.Onpaint();
事件发生的顺序为:
1,无论客户区何时变为无效,都应该调用OnPaint方法,这是HelloWorld中的OnPaint调用Form中的ONpaint;
2,HelloWorld中的OnPaint方法调用基类中的OnPaint方法,虽然那通常是Form中的方法,但是很有可能from并没有覆盖control中的OnPaint方法,调用的实质还是调用Control中的Onpaint方法。
3,Control中的Onpaint方法调用所有已经安装过的Paint事件处理方法。在调用所有已经安装的paint事件处理方法后,Control中的onPaint
返回到HelloWorld的Onpaint中