看到博文實現自定義 Panel 邊框,不知代碼放哪:重寫控件?寫在類裡?
using System.Windows.Forms;
using System.Drawing;
public class CustomBorderPanel : Panel {
public CustomBorderPanel() {
this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
// 邊框屬性
public Color BorderColor { get; set; } = Color.Gray;
public int BorderWidth { get; set; } = 1;
public BorderStyle CustomBorderStyle { get; set; } = BorderStyle.FixedSingle;
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
if (CustomBorderStyle != BorderStyle.None) {
using (Pen pen = new Pen(BorderColor, BorderWidth)) {
Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
e.Graphics.DrawRectangle(pen, rect);
}
}
}
}
CustomBorderPanel 圖標。BorderColor、BorderWidth 等。[Designer(typeof(ScrollableControlDesigner))] // 支持設計時滾動
[ToolboxBitmap(typeof(Panel))] // 用 Panel 圖標
public class CustomBorderPanel : Panel { ... }
**核心點:繼承控件 → 重寫 OnPaint → Build → 工具箱自動顯示 → 拖放使用。**