/// <summary>
/// keypress事件控制输入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void decimal_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.' ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
{
int precision = 3;
int scale = 0;
TextBox textBox = sender as TextBox;
if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.')
{
if (scale == 0 && e.KeyChar == '.')
{
// 没有小数部的时候,小数点输入不可
e.Handled = true;
}
else if (textBox.Text.Contains(".") && e.KeyChar == '.')
{
// 已经输入'.'的时候,'.'输入不可
e.Handled = true;
}
else
{
// 除开上面的情况,对整数部和小数部的位数检查
string newString = textBox.Text.Substring(0, textBox.SelectionStart) + e.KeyChar +
textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength);
if (newString.Contains("."))
{
// 有小数点的时候
string[] splits = newString.Split('.');
if (splits.Length > 1)
{
if (splits[0].Length > precision)
{
e.Handled = true;
}
else if (splits[1].Length > scale)
{
e.Handled = true;
}
}
}
else
{
// 没有小数点的时候
if (newString.Length > precision)
{
e.Handled = true;
}
}
}
}
}
else
{
// 数字以外输入的时候
e.Handled = true;
}
}