自定义文本框
/// <summary>
/// 自定义文本框
/// 1.只能输入数值, 限制输入两位小数
/// 2.禁止粘贴
/// </summary>
public class ExTextBoxFloat : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar != 8)
{
if (this.Text.Length == 4)//限制长度为4
e.Handled = true;
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != '.')
e.Handled = true;
// 小数点只能输入一次
if (e.KeyChar == '.' && this.Text.IndexOf('.') != -1)
{
e.Handled = true;
}
// 第一位不能为小数点
if (e.KeyChar == '.' && this.Text == "")
{
e.Handled = true;
}
// 第一位是0,第二位必须为小数点
if (e.KeyChar != '.' && this.Text == "0")
{
e.Handled = true;
}
// 有小数只保留2位
if (this.Text.IndexOf('.') != -1)
{
if (this.Text.Length - this.Text.IndexOf('.') - 1 == 2)
{
e.Handled = true;
}
}
}
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0302)//0x0302 是粘贴消息
{
m.Result = IntPtr.Zero;//拦截消息
return;
}
base.WndProc(ref m);//如果不是粘贴消息,则交给其它基类处理
}
}
调用
定义好文本框后,直接在工具箱界面中拖出定义好的新文本框控件即可。