在C# WinForm中,自定義控件的樣式通常需要重寫控件的OnPaint方法。以下是一個(gè)簡(jiǎn)單的示例,展示了如何為Button控件創(chuàng)建自定義樣式:
CustomButton
。CustomButton.cs
文件以打開設(shè)計(jì)器。在設(shè)計(jì)器中,從工具箱中刪除默認(rèn)的Label控件。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);
}
}
}
CustomButton.cs
文件。CustomButtonDemo
。CustomButtonDemo
項(xiàng)目中,從工具箱中添加一個(gè)CustomButton
控件到主窗體上。CustomButtonDemo
項(xiàng)目,查看自定義按鈕樣式。這個(gè)示例展示了如何為Button控件創(chuàng)建自定義樣式。你可以根據(jù)需要修改OnPaint
方法中的代碼來(lái)實(shí)現(xiàn)不同的樣式。