ลองดูตัวอย่างนะครับ
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //เมื่อมีการคลิกที่ Button
{
Graphics g = this.CreateGraphics();
MyPaint(g); //เรียกใช้เมธอด
}
protected void MyPaint(Graphics g) //สร้างเมธอดขึ้นมาใหม่โดยรับค่าเป็น object ของคลาส Graphics
{
g = this.CreateGraphics();
g.FillRectangle(Brushes.CadetBlue, new Rectangle(10, 10, 100, 100));
}
}
}
ผลลัพธ์
รูปก่อนที่จะ Click ที่ Button
รูปหลังจากที่ Click ที่ Button แล้ว
และถ้าต้องการส่งค่าอื่นๆเช่น ขนาดและสี ไปให้กับเมธอดเพื่อวาดรูป rectangle ตามค่าที่รับเข้ามาก็เขียนได้ดังนี้
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Graphics g = this.CreateGraphics();
MyPaint(g,30,25,115,200,Brushes.Red); //เรียกใช้เมธอดและมีการส่งค่าขนาดของรูป Rectangle และสี Background
}
protected void MyPaint(Graphics g,int x1,int y1,int x2,int y2,Brush b) //สร้างเมธอดขึ้นมาใหม่โดยรับค่าเป็น object ของคลาส Graphics และค่าอื่นๆเช่นขนาดของรูปและสี
{
g = this.CreateGraphics();
g.FillRectangle(b, new Rectangle(x1,y1,x2,y2)); //วาดรูปตามค่าที่รับเข้ามา
}
}
}
ผลลัพธ์
รูปก่อนที่จะคลิกที่ Button
รูปหลังจากที่คลิกที่ Button แล้ว

[With great power comes great responsibility]