錯誤代碼
PicForm frm = new PicForm();
Graphics g = frm.pictureBox1.CreateGraphics(); // 窗體未顯示,Handle 未創建
g.DrawLine(...);
frm.Show();
原因
- `CreateGraphics()` 依賴控件已創建窗口句柄(`IsHandleCreated == true`),`new Form()` 後未 `Show` 句柄不存在。
- 即使句柄存在,**繪圖內容在重繪時會丟失**(WM_PAINT 不會保留手動繪製內容)。
正確模式:數據驅動繪圖
// PicForm.cs
public class PicForm : Form {
private List lines = new List();
public void AddLine(Point p1, Point p2, Color c) {
lines.Add(new LineData(p1, p2, c));
pictureBox1.Invalidate(); // 觸發重繪
}
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
foreach (var l in lines)
using (var pen = new Pen(l.Color, 2))
e.Graphics.DrawLine(pen, l.P1, l.P2);
}
}
// 調用方
PicForm frm = new PicForm();
frm.AddLine(new Point(100,150), new Point(120,200), Color.Red);
frm.Show();
核心原則
- **所有繪圖邏輯集中在 `Paint` 事件** 中,使用 `e.Graphics`。
- 狀態(線條、顏色、座標)存儲在窗體字段/屬性中。
- 需要更新時修改狀態並調用 `Invalidate()` / `Refresh()`。