1.简单用户输入内容实时显示功能:
public class LabelTextOne:UserControl
{
private Label _Label;
private TextBox _TextBox;
public LabelTextOne()
{
InitializeComponnet();
}
public void InitializeComponnet()
{
//定义一个 标签
_Label = new Label();
_Label.Location = new System.Drawing.Point(0,0);
_Label.Size = new System.Drawing.Size(100,20);
this.Controls.Add(_Label);
//定义一个 文本框
_TextBox = new TextBox();
_TextBox.Location = new Point(105,0);
_TextBox.Size = new Size(100,20);
_TextBox.TextChanged += _TextBox_TextChanged;
this.Controls.Add(_TextBox);
//当前控件初始化
this.Size = new Size(205,20);
this.BorderStyle = BorderStyle.Fixed3D;
}
//当输入框内容发生改变是
void _TextBox_TextChanged(object sender, EventArgs e)
{
TextBox box = sender as TextBox;
if (box != null)
{
LabelText = Text;
}
}
//扩展属性
public override string Text
{
get
{
return _TextBox.Text;
}
set
{
_TextBox.Text = value;
}
}
public string LabelText
{
get { return _Label.Text; }
set { _Label.Text = value; }
}
}
使用方法,显示结果:
加载到工具箱中可以直接拖动使用
2.自定义控件控制 边框
public class MyBorder:UserControl
{
private int _BorderSize = 1;
public int BorderSize
{
get { return _BorderSize; }
set { _BorderSize = value; }
}
private Color _BorderColor = Color.Blue;
public Color BorderColor
{
get { return _BorderColor; }
set { _BorderColor = value; }
}
public MyBorder()
{
InitializeComponent();
}
public void InitializeComponent()
{
//初始化控件
this.Size = new Size(50,50);
this.BackColor = Color.LightGray;
}
protected override void OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
Graphics g = e.Graphics;
Rectangle rect = e.ClipRectangle;
Pen p = new Pen(_BorderColor, _BorderSize);
//设置 巨型的宽
rect.Width = rect.Width - _BorderSize / 2;
rect.Height = rect.Height - _BorderSize / 2;
g.DrawRectangle(p, rect);
}
}
使用和显示结果:
private void Form1_Load(object sender, EventArgs e)
{
MyBorder.MyBorder border = new MyBorder.MyBorder();
border.Location = new Point(50, 50);
border.Size = new Size(200, 200);
border.BorderColor = Color.Red;
border.BorderSize = 3;
this.Controls.Add(border);
}