转载:https://blog.csdn.net/qq_48705696/article/details/108929310
1.为文本框添加KeyPress事件:
2.输入限制的原理:将输入值转化为ACSII的值进行限制,附上ACSII表
(我猜你看不清这图片,在图片上右击——>新标签页中打开图片)
3.原理大致明了了,接下来编程
/// <summary> /// KeyPress事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { limit_txtinput(sender, e); } private void limit_txtinput(object sender, KeyPressEventArgs e) { //ACSII中48-57表示数字:0-9 //ACSII中8表示退格键(删除键) //ACSII中46表示小数点 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46) e.Handled = true; //小数点的处理。 if ((int)e.KeyChar == 46) //小数点 { if (this.Text.Length <= 0) e.Handled = true; //小数点不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(this.Text, out oldf); b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } }
4.原作者的可输入负号版本(只转载,未经验证)
private void t_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = limit_txtinput(sender, e); } //限制txtBox的输入内容仅可为数字和小数点(小数点不能是首位) private bool limit_txtinput(object sender, KeyPressEventArgs e) { //允许输入数字、小数点、删除键和负号 if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-')) return true; if (e.KeyChar == (char)('-')) { if ((sender as TextBox).Text != "") return true; } //小数点只能输入一次 if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1) return true; //第一位不能为小数点 if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "") return true; //第一位是0,第二位必须为小数点 if (e.KeyChar != (char)('.') && e.KeyChar != 8 && ((TextBox)sender).Text == "0") return true; //第一位是负号,第二位不能为小数点 if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.')) return true;
return false; }