c# winform控件如何自定義樣式

c#
小樊
84
2024-08-27 14:44:27

在C# WinForm中,自定義控件的樣式通常需要重寫控件的OnPaint方法。以下是一個(gè)簡(jiǎn)單的示例,展示了如何為Button控件創(chuàng)建自定義樣式:

  1. 首先,創(chuàng)建一個(gè)新的C# WinForms項(xiàng)目。
  2. 在解決方案資源管理器中,右鍵單擊項(xiàng)目名稱,然后選擇“添加”->“用戶控件”。將新的用戶控件命名為CustomButton。
  3. 雙擊CustomButton.cs文件以打開設(shè)計(jì)器。在設(shè)計(jì)器中,從工具箱中刪除默認(rèn)的Label控件。
  4. 打開CustomButton.cs文件的代碼視圖,并添加以下代碼:
using System;
using System.Drawing;
using System.Windows.Forms;

public partial class CustomButton : UserControl
{
    public CustomButton()
    {
        InitializeComponent();
        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // 自定義按鈕樣式
        Graphics g = e.Graphics;
        Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
        Color borderColor = Color.FromArgb(50, 50, 50);
        Color fillColor = Color.FromArgb(80, 80, 80);
        Color textColor = Color.White;

        if (this.Enabled)
        {
            if (this.Focused || this.ContainsFocus)
            {
                borderColor = Color.Blue;
                fillColor = Color.FromArgb(100, 100, 100);
            }
            else if (this.ClientRectangle.Contains(this.PointToClient(Cursor.Position)))
            {
                borderColor = Color.Gray;
                fillColor = Color.FromArgb(90, 90, 90);
            }
        }
        else
        {
            borderColor = Color.DarkGray;
            fillColor = Color.FromArgb(60, 60, 60);
            textColor = Color.Gray;
        }

        using (SolidBrush brush = new SolidBrush(fillColor))
        {
            g.FillRectangle(brush, rect);
        }

        using (Pen pen = new Pen(borderColor, 1))
        {
            g.DrawRectangle(pen, rect);
        }

        StringFormat format = new StringFormat
        {
            Alignment = StringAlignment.Center,
            LineAlignment = StringAlignment.Center
        };

        using (SolidBrush brush = new SolidBrush(textColor))
        {
            g.DrawString(this.Text, this.Font, brush, this.ClientRectangle, format);
        }
    }
}
  1. 保存并關(guān)閉CustomButton.cs文件。
  2. 在解決方案資源管理器中,右鍵單擊項(xiàng)目名稱,然后選擇“添加”->“新建項(xiàng)目”。選擇“Windows Forms應(yīng)用程序”模板,并將其命名為CustomButtonDemo。
  3. CustomButtonDemo項(xiàng)目中,從工具箱中添加一個(gè)CustomButton控件到主窗體上。
  4. 運(yùn)行CustomButtonDemo項(xiàng)目,查看自定義按鈕樣式。

這個(gè)示例展示了如何為Button控件創(chuàng)建自定義樣式。你可以根據(jù)需要修改OnPaint方法中的代碼來(lái)實(shí)現(xiàn)不同的樣式。

0