OnPaint(PaintEventArgs e) 參數提供兩大核心屬性:
Draw*/Fill* 族群方法、座標轉換、品質設定。protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e); // 必須呼叫基類
// 1. 建立橢圓路徑(客戶區扣 1 像素避免邊框被切)
using (GraphicsPath path = new GraphicsPath()) {
path.AddEllipse(0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
// 2. 填充背景(懸停/正常雙色系)
using (SolidBrush b = new SolidBrush(bolMouseHoverFlag ? HoverBackColor : ButtonBackColor))
e.Graphics.FillPath(b, path);
// 3. 繪製邊框(懸停/正常雙色系,寬度 2)
using (Pen p = new Pen(bolMouseHoverFlag ? HoverBorderColor : BorderColor, 2))
e.Graphics.DrawPath(p, path);
}
// 4. 繪製文字(置中、單行)
if (Caption != null) {
using (StringFormat f = new StringFormat()) {
f.Alignment = StringAlignment.Center;
f.LineAlignment = StringAlignment.Center;
f.FormatFlags = StringFormatFlags.NoWrap;
using (SolidBrush b = new SolidBrush(ForeColor))
e.Graphics.DrawString(Caption, Font, b,
new RectangleF(0, 0, ClientSize.Width, ClientSize.Height), f);
}
}
}
ClientSize.Width - 1:確保寬度為奇數時橢圓邊框不被切邊。using 巢狀包裹:保證 GraphicsPath、Brush、Pen、StringFormat 全部及時釋放。base.OnPaint(e):若省略,父類背景繪製邏輯將缺失,可能導致殘影。編譯專案後,工具箱「我的使用者控件」自動出現 EllipseButton。拖放至表單、設定 Caption 屬性、執行——得到一個**靜態但完美圓潤**的橢圓按鈕。**動態效果待下節注入滑鼠邏輯後誕生**。