温馨提示×

c# winform控件如何自定义样式

c#
小樊
166
2024-08-27 14:44:27
栏目: 编程语言

在C# WinForm中,自定义控件的样式通常需要重写控件的OnPaint方法。以下是一个简单的示例,展示了如何为Button控件创建自定义样式:

  1. 首先,创建一个新的C# WinForms项目。
  2. 在解决方案资源管理器中,右键单击项目名称,然后选择“添加”->“用户控件”。将新的用户控件命名为CustomButton
  3. 双击CustomButton.cs文件以打开设计器。在设计器中,从工具箱中删除默认的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. 保存并关闭CustomButton.cs文件。
  2. 在解决方案资源管理器中,右键单击项目名称,然后选择“添加”->“新建项目”。选择“Windows Forms应用程序”模板,并将其命名为CustomButtonDemo
  3. CustomButtonDemo项目中,从工具箱中添加一个CustomButton控件到主窗体上。
  4. 运行CustomButtonDemo项目,查看自定义按钮样式。

这个示例展示了如何为Button控件创建自定义样式。你可以根据需要修改OnPaint方法中的代码来实现不同的样式。

0