自 定 义 控 件 自定义控件 自定义控件
1.自定义控件
自定义控件的三种方式:
1 复合控件:将标准控件组合起来
class YourControl : UserControl{}
2 扩展控件:继承于标准控件
class YourControl : Button {}
3 自定义控件:完全地自定义一个控件
class YourControl : Control {}
继承于Control类,就可以从头到尾定制一个控件
包含以下几个方面:
1 控件的显示(绘制)
2 控件的行为(事件)
3 控件的数据(属性)
自定义控件,是WinForm界面技术的重点
演示:添加一个自定义控件
- 1 添加MyConjtrol类,继承于Control注意选择
System.Windows.Forms.Control
- 2 重新生成项目解决方案
- 3 重新打开Form1.cs,在工具箱里即可显示此控件
如果在工具箱里不显示,则需要设置一下
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Winform自定义控件
{
class MyControl:Control
{
public MyControl()
{
this.BackColor = Color.Pink;
this.Size = new Size(100, 100);
}
}
}
2.控件的绘制
重写
OnPaint()
方法,实现控件的绘制
演示:在控件里绘制一个红色的矩形
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Winform自定义控件
{
class MyControl:Control
{
public MyControl()
{
this.BackColor = Color.Pink;
this.Size = new Size(100, 100);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Red);
g.DrawRectangle(pen, 0, 0, 30, 30);
pen.Dispose();
}
}
}
OnPaint()的实现:
- 1 一般需要先调用
base.OnPaint()
- 2 Graphics是绘制工具,提供多个绘制API
- 3 笔Pen ,用于指定线条参数(颜色、宽度、线型)
注意:Pen中包含非托管资源,需要手工Dispose()
OnPaint方法是由WinForm系统框架调用的,不可自己调用。
3.颜色与坐标
WinForm里的颜色,特指RGB颜色空间( ColorSpace)
自然界的颜色由三原色组成:红绿蓝
比如,
白色=(255, 255,255)
黑色=(0,0,0)
红色=(255,0,0)
黄色=(255, 255,0)
其中,R,G,B三个分量的范围是0-255
指定颜色有两种方式:
Color color = Color.White ;
或者
Color color = Color. FromArgb( 255,255,255);
具体颜色的选择,可以百度RGB颜色表,或者使用拾色器
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
Color color = Color.FromArgb(255,0,0);
Pen pen = new Pen(color);
g.DrawRectangle(pen, 0, 0, 30, 30);
pen.Dispose();
}
颜色透明度:Alpha
实际在指定颜色时,是A,R, G,B四个分量
Alpha=0,表示全透明
Alpha = 255,表示不透明
比如,
Color clr = Color.FromArgb( 120,255,255,O);
其中,透明度alpha为 120
坐标
在OnPaint()中绘制时,要提供相关坐标
此坐标是相对于控件自身的坐标,(0,0)
指的是控件自己的左上角。