您的位置:首页 > 编程语言 > C#

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

2016-11-21 23:06 337 查看
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);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: