首先给出原代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace 导Excel控件
{
class myLabel : Label
{
TextBox myText = new TextBox();
Panel myPanel = new Panel();
public myLabel()
{
// 初始化文本框控件
myText.Visible = false;
myText.Location = this.Location;
myText.BorderStyle = BorderStyle.None;
// 重写 myText 控件的单击事件
this.myText.KeyPress += new KeyPressEventHandler(myText_KeyPress);
// 重写 myLabel 控件的单击事件
this.Click += new EventHandler(myLabel_Click);
this.Leave += new System.EventHandler(myText_Leave);
// 将 myText 控件添加到 myLabel 控件中
this.Controls.Add(myText);
}
private void myLabel_Click(object sender, EventArgs e)
{
myText.Size = this.Size;
myText.Text = this.Text;
myText.Visible = true;
myText.Focus();
//MessageBox.Show("myLabel click!");
}
private void myText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.Text = myText.Text;
this.myText.Visible = false;
}
//MessageBox.Show("myText_KeyPress event!");
}
private void myText_Leave(object sender, EventArgs e)
{
this.Text = myText.Text;
this.myText.Visible = false;
//MessageBox.Show("myText Lost Focus!");
}
}
}
可以看到:
// 将 myText 控件添加到 myLabel 控件中
this.Controls.Add(myText);
这条语句至关重要,另外我们在这里面涉及到了如何重载控件的事件,但一定要注意,在该类的构造函数中所有关于该类的属性值的设置和获取都会变为无效,具体原因是我们这在这里只是构造了这么一个对象,但是到了构造函数完成之后,创建该对象的程序都会对该对象再进行一次属性设置,所以,假设我们想得到该类的大小或位置时,在构造函数里面设置往往达不到效果。
利用这个原理,我们还可以生成带有 Label 显示效果,但功能如 DateTimePicker ,有选择日期功能的超级 Label 控件。