封裝自定義控件很簡單,沒什麼技術含量,這裡通過封裝自定義的數字文本框實例簡單總結一下:
【1】新建自定義控件庫 -- Windows Forms Control Library

【2】添加自定義組件 -- Component Class

【3】繼承TextBox,添加KeyPress事件,代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinForms.SelfControl
{
///
/// 數字文本框 -- 如果生成的Dll在工具箱中導入不了,可以直接將Dll拖入
///
public partial class TextBoxNumber : TextBox
{
public TextBoxNumber()
{
InitializeComponent();
}
public TextBoxNumber(IContainer container)
{
container.Add(this);
InitializeComponent();
this.KeyPress += TextBoxNumber_KeyPress;
}
///
/// 只能輸入數字
///
void TextBoxNumber_KeyPress(object sender, KeyPressEventArgs e)
{
//如果輸入的不是數字鍵,也不是回車鍵、Backspace鍵,則取消該輸入
if ( !(Char.IsNumber(e.KeyChar)) &&
e.KeyChar != (char)13 &&
e.KeyChar != (char)8 )
{
e.Handled = true;
}
}
}
}

【5】測試自定義的控件 -- 驗證是否只能輸入數字

【6】注意問題
必須采用AnyCPU編譯,如果生成的Dll導入到工具箱有問題,可以直接將文件拖入。。。
源碼:
http://download.csdn.net/detail/aoshilang2249/8172891