4 C 程式設計學習——窗體Paint事件處理程式
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
4.C#程式設計學習——窗體Paint事件處理程式
原始碼
usingSystem;
usingSystem.Drawing;
usingSystem.Windows.Forms;
classPaintEvent
{
publicstaticvoid Main()
{
Form form =newForm();
form.Text ="Paint Event";
form.Paint +=newPaintEventHandler
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);
}
}