//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 && (int)e.KeyChar !=45 )
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46){ //小数点
if (txtAdjustment.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else{ //处理不规则的小数点
char strAdjustment = Convert.ToChar(txtAdjustment.Text.Substring(0,1));
if((int)strAdjustment == 45 && txtAdjustment.Text.Length == 1) //小数点不能在负号后面
e.Handled = true;
else{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(txtAdjustment.Text, out oldf);
b2 = float.TryParse(txtAdjustment.Text + e.KeyChar.ToString(), out f);
if (b2 == false){
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}else if((int)e.KeyChar == 45){ //负号
if (txtAdjustment.Text.Length >= 1)
e.Handled = true; //负号只能在第一位
}
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 && (int)e.KeyChar !=45 )
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46){ //小数点
if (txtAdjustment.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else{ //处理不规则的小数点
char strAdjustment = Convert.ToChar(txtAdjustment.Text.Substring(0,1));
if((int)strAdjustment == 45 && txtAdjustment.Text.Length == 1) //小数点不能在负号后面
e.Handled = true;
else{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(txtAdjustment.Text, out oldf);
b2 = float.TryParse(txtAdjustment.Text + e.KeyChar.ToString(), out f);
if (b2 == false){
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}else if((int)e.KeyChar == 45){ //负号
if (txtAdjustment.Text.Length >= 1)
e.Handled = true; //负号只能在第一位
}
参考文档:http://blog.sina.com.cn/s/blog_a9091a33010162iv.html