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

C# WinForms Button 點擊設置 Panel 邊框顏色:Paint 事件繪製邊框

     編輯:程式設計綜合問答

核心思路

Panel 無直接 BorderColor 屬性,需在 Paint 事件中用 Graphics.DrawRectangle 繪製,按鈕點擊修改顏色字段並調用 Invalidate() 觸發重繪。

完整代碼


public partial class Form1 : Form {
    private Color panelBorderColor = Color.Black; // 默認顏色

    public Form1() {
        InitializeComponent();
        panel1.Paint += Panel1_Paint;
        btnChangeColor.Click += BtnChangeColor_Click;
    }

    private void Panel1_Paint(object sender, PaintEventArgs e) {
        using (Pen pen = new Pen(panelBorderColor, 2)) { // 寬度 2 像素
            e.Graphics.DrawRectangle(pen, 0, 0, panel1.Width - 1, panel1.Height - 1);
        }
    }

    private void BtnChangeColor_Click(object sender, EventArgs e) {
        using (ColorDialog dlg = new ColorDialog()) {
            if (dlg.ShowDialog() == DialogResult.OK) {
                panelBorderColor = dlg.Color;
                panel1.Invalidate(); // 觸發 Paint 事件
            }
        }
    }
}

關鍵點

  • panel1.Paint 事件中繪製,座標 (0,0) 到 (Width-1, Height-1) 避免右/下邊框被切掉。
  • Invalidate() 標記控件需重繪,系統會異步調用 Paint。
  • 用 ColorDialog 讓用戶選顏色,或直接指定 Color.Red 等常量。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved