using System;
using System.Drawing;
using System.Windows.Forms;
// 自定义控件示例:一个简单的圆形按钮
public class CircleButton : Control
{
private string text = "Circle Button";
private Color backgroundColor = Color.LightBlue;
private Color borderColor = Color.Black;
private int borderWidth = 2;
// 构造函数
public CircleButton()
{
this.Size = new Size(100, 100);
this.BackColor = Color.Transparent;
}
// 属性设置
public string Text
{
get { return text; }
set { text = value; Invalidate(); }
}
public Color BackgroundColor
{
get { return backgroundColor; }
set { backgroundColor = value; Invalidate(); }
}
public Color BorderColor
{
get { return borderColor; }
set { borderColor = value; Invalidate(); }
}
public int BorderWidth
{
get { return borderWidth; }
set { borderWidth = value; Invalidate(); }
}
// 绘制控件
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// 绘制背景
using (Brush brush = new SolidBrush(backgroundColor))
{
g.FillEllipse(brush, ClientRectangle);
}
// 绘制边框
using (Pen pen = new Pen(borderColor, borderWidth))
{
Rectangle rect = ClientRectangle;
rect.Inflate(-borderWidth / 2, -borderWidth / 2);
g.DrawEllipse(pen, rect);
}
// 绘制文本
using (Brush brush = new SolidBrush(ForeColor))
{
SizeF size = g.MeasureString(text, Font);
PointF point = new PointF((ClientRectangle.Width - size.Width) / 2,
(ClientRectangle.Height - size.Height) / 2);
g.DrawString(text, Font, brush, point);
}
}
// 处理鼠标点击事件
protected override void OnClick(EventArgs e)
{
MessageBox.Show("Circle Button Clicked!");
base.OnClick(e);
}
}
// 使用自定义控件的示例
public class MainForm : Form
{
public MainForm()
{
CircleButton circleButton = new CircleButton();
circleButton.Text = "Click Me!";
circleButton.Location = new Point(50, 50);
this.Controls.Add(circleButton);
this.ClientSize = new Size(200, 200);
this.Text = "Custom Control Example";
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
CircleButton 类:
Control 类,创建一个圆形按钮。Text, BackgroundColor, BorderColor, 和 BorderWidth,用于设置按钮的样式。OnPaint 方法来绘制圆形按钮,使用 Graphics 对象绘制背景、边框和文本。OnClick 方法来处理按钮点击事件。MainForm 类:
CircleButton 到窗体中。Main 方法中启动应用程序。上一篇:c# int
下一篇:c# continue
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站