在按鈕點擊事件中直接呼叫 `Graphics.DrawEllipse` 並 `Thread.Sleep` 動畫,會導致:視窗遮擋/最小化後圖形消失、UI 凍結、重繪邏輯混亂。
// 表單層級欄位
private List circles = new List();
private Random rand = new Random();
// 圓形資料類別
class Circle {
public int X, Y, R;
public Color PenColor;
public Circle(int x, int y, int r, Color c) { X=x; Y=y; R=r; PenColor=c; }
}
// Paint 事件:所有繪圖邏輯集中於此
private void Form1_Paint(object sender, PaintEventArgs e) {
foreach (var c in circles) {
using (Pen pen = new Pen(c.PenColor, 2)) {
e.Graphics.DrawEllipse(pen, c.X, c.Y, c.R, c.R);
}
}
}
// 按鈕點擊:只修改資料並觸發重繪
private void btnAddCircle_Click(object sender, EventArgs e) {
Color randomColor = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
circles.Add(new Circle(50, 50 + circles.Count * 30, 20, randomColor));
this.Invalidate(); // 標記需重繪,觸發 Paint 事件
}
// 動畫效果:使用 Timer 而非 Sleep
private void btnAnimate_Click(object sender, EventArgs e) {
Timer timer = new Timer { Interval = 50 };
int step = 0;
timer.Tick += (s, args) => {
if (step++ > 20) { timer.Stop(); return; }
circles[0].X += 5; // 移動第一個圓
this.Invalidate();
};
timer.Start();
}
遵循此模式,即可實現流暢、穩定、可維護的自繪圖形與動畫。