加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

有趣的C#中OnPaint事件

(2011-04-06 17:21:14)
标签:

杂谈

分类: .NET
先看下边的两段程序:

程序段1:
using System;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
class HelloWorld : Form
{
    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);
    }

}

程序段2:
using System;
using System.Windows;
using System.Drawing;
using System.Windows.Forms;
class InheritHelloWorld
{
    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);
    }
}


这段程序的最终现实结果为: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中

0

阅读 收藏 喜欢 打印举报/Report
前一篇:处理Paint事件
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有