首先給出原代碼:
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 控件。