自 定 义 事 件 自定义事件 自定义事件
1.自定义事件
自定义控件的三个方面:
- 显示(绘制)
- 数据(属性)
行为(事件)
public class MyButton : Control
{
private string text;
public MyButton()
{
//this.BackColor = Color.White;
this.Size = new Size(200, 100);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
int w = this.Width, h = this.Height;
Rectangle rect = new Rectangle(0, 0, w, h);
// 平滑绘制
g.SmoothingMode = SmoothingMode.HighQuality;
rect.Inflate(-2, -2);
// 背景及边框线
using (Brush brush = new SolidBrush(Color.FromArgb(255, 255, 255)))
{
AfGraphicUtil.FillRoundRectangle(g, brush, rect, 20);
}
using (Pen pen = new Pen(Color.LightBlue))
{
AfGraphicUtil.DrawRoundRectangle(g, pen, rect, 20);
}
// 文字
using (Brush brush = new SolidBrush(Color.FromArgb(0x22, 0x22, 0x22)))
{
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
g.DrawString(text, this.Font, brush, rect, format);
}
}
// 属性
public override string Text
{
get
{
return text;
}
set
{
this.text = value;
this.Invalidate();
}
}
//
public event EventHandler MyClickEvent;
//
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
//
MyClickEvent?.Invoke(this, e);
}
}
//
public event EventHandler MyClickEvent;
//
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
//
MyClickEvent?.Invoke(this, e);
}
Control类本身就有基础的鼠标和键盘事件
这里只是一个引子,用于引出更复杂的自定义事件