在C# WinForm中,自定义控件的样式通常需要重写控件的OnPaint方法。以下是一个简单的示例,展示了如何为Button控件创建自定义样式:
CustomButton
。CustomButton.cs
文件以打开设计器。在设计器中,从工具箱中删除默认的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
项目中,从工具箱中添加一个CustomButton
控件到主窗体上。CustomButtonDemo
项目,查看自定义按钮样式。这个示例展示了如何为Button控件创建自定义样式。你可以根据需要修改OnPaint
方法中的代码来实现不同的样式。