首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

WinForm Panel 邊框自定義:繼承控件並加入工具箱

     編輯:程式設計綜合問答

問題

看到博文實現自定義 Panel 邊框,不知代碼放哪:重寫控件?寫在類裡?

標準做法:繼承 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);
            }
        }
    }
}

關鍵步驟:編譯後自動進工具箱

  1. 在項目中添加上述類文件。
  2. **Build Solution (Ctrl+Shift+B)**。
  3. 打開設計器,**工具箱 → "CustomBorderPanel Components" (或項目名) 節點** → 會出現 CustomBorderPanel 圖標。
  4. 直接拖放到窗體,像原生 Panel 一樣使用,屬性窗口可設置 BorderColor、BorderWidth 等。

進階:設計時體驗優化

[Designer(typeof(ScrollableControlDesigner))] // 支持設計時滾動
[ToolboxBitmap(typeof(Panel))] // 用 Panel 圖標
public class CustomBorderPanel : Panel { ... }

**核心點:繼承控件 → 重寫 OnPaint → Build → 工具箱自動顯示 → 拖放使用。**

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved