最近老师傅让我帮他搞wpf的项目,我还是饶有兴趣的,要知道wpf在C/S端可是很受欢迎啊,我索性也就接过了,废话不多说,其中有一个textbox的控件,是输入金额的,查了很多参照了一些博客https://www.cnblogs.com/yuzhou133/p/4112539.html
其中调用部分应该用在哪呢?看我的博客吧,反正小编是成功了
private void txtsite_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.NumPad0:
case Keys.NumPad1:
case Keys.NumPad2:
case Keys.NumPad3:
case Keys.NumPad4:
case Keys.NumPad5:
case Keys.NumPad6:
case Keys.NumPad7:
case Keys.NumPad8:
case Keys.NumPad9:
case Keys.Back:
case Keys.OemPeriod:
case Keys.Delete:
case Keys.Decimal:
e.SuppressKeyPress = false;
break;
default:
break;
}
}
private void txtsite_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tBox = sender as TextBox;
char c = e.KeyChar;
if (c.ToString().Equals("."))
{
if (tBox.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(tBox.Text, out oldf);
b2 = float.TryParse(tBox.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
ShieldNumberTextBoxOtherKeys(tBox);//在此处调用即可
}
public virtual void ShieldNumberTextBoxOtherKeys(TextBox tbox)
{
tbox.ImeMode = ImeMode.Disable;
tbox.KeyDown += txtsite_KeyDown;
tbox.KeyPress += txtsite_KeyPress;
}
寻寻觅觅,小编昨天在做这个功能的时候突然发现这个功能是有问题的,即第一次录入信息的时候录入的是汉字也可以录入,小编真是炸了,然后又查找了一些资料,参考地址https://bbs.csdn.net/topics/240038271?list=lz
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == '.'))
{
e.Handled = true;
// MessageBox.Show("请输入数字");
}
}
就是这么简单,小编在做的时候发现弹出提示会有重复,因此小编直接将弹出的提示屏蔽掉了,效果也是不错的