4.C#编程学习——窗体Paint事件处理程序

4.C#编程学习——窗体Paint事件处理程序

源码

usingSystem;

usingSystem.Drawing;

usingSystem.Windows.Forms;

 

classPaintEvent

{

    publicstaticvoid Main()

    {

        Form form = newForm();

        form.Text = "Paint Event";

        form.Paint += newPaintEventHandler(MyPaintHandler);

 

        Application.Run(form);

    }

    staticvoid MyPaintHandler(object objSender, PaintEventArgs pea)

    {

        Graphics grfx = pea.Graphics;

 

        grfx.Clear(Color.Chocolate);

    }

}

         当在Main中创建窗体之后,名为MyPaintHandler方法附加到这个窗体的Paint事件中。

         从PaintEventArgs类获得一个Graphics对象,并使用它来调用Clear方法。

Paint事件

         相当频繁、有时出乎意料到调用这个方法。可以不中断的快速重新绘制客户区。

多个窗体

usingSystem;

usingSystem.Drawing;

usingSystem.Windows.Forms;

 

classPaintTwoForms

{

    staticForm form1, form2;

 

    publicstaticvoid Main()

    {

        form1 = newForm();

        form2 = newForm();

 

        form1.Text = "First Form";

        form1.BackColor = Color.White;

        form1.Paint += newPaintEventHandler(MyPaintHandler);

 

        form2.Text = "Second Form";

       form2.BackColor = Color.White;

        form2.Paint += newPaintEventHandler(MyPaintHandler);

        form2.Show();

 

        Application.Run(form1);

    }

    staticvoid MyPaintHandler(object objSender, PaintEventArgs pea)

    {

        Form form = (Form)objSender;

        Graphics grfx = pea.Graphics;

        string str;

 

        if (form == form1)

            str = "Hello from the first form";

        else

            str = "Hello from the second form";

 

        grfx.DrawString(str, form.Font, Brushes.Black, 0, 0);

    }

}

OnPaint方 法

         通过继承Form而不只是创建一个实例可以获得一些好处。

源码

usingSystem;

usingSystem.Drawing;

usingSystem.Windows.Forms;

 

classHelloWorld : Form

{

    publicstaticvoid Main()

    {

        Application.Run(newHelloWorld());

    }

    public HelloWorld()

    {

        Text = "Hello World";

        BackColor = Color.White;

    }

    protectedoverridevoid OnPaint(PaintEventArgs pea)

    {

        Graphics grfx = pea.Graphics;

 

        grfx.DrawString("Hello, Windows Forms!", Font, Brushes.Black, 0, 0);

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值