仅输入数字和控制按钮

Input only digits and control buttons

我想输入 Salary 任意值:550,492222,129,3 等等。但是需要这样使用控制按钮:,backspacectrl + cctrl + vctrl + a.

SalaryTextBoxShortcutsEnabled = true 和事件:

private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
    char number = e.KeyChar;
    if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44) 
         //digits, BackSpace and ,
    {
        e.Handled = true;
    }
}

如果删除此条件,指定的组合将起作用。但不仅输入了数字。

我应该在这里添加所有组合的跟踪吗?或者是否可以通过其他方式实现此任务?

MaskedTextBox 需要固定数量的字符,其中一些 "mask"。但是 Salary 是不同的。可以是 **,********,****

更新

防止在小数点后输入两个以上的数字

if (number < ' ')
{
    return;
}
if (number >= '0' && number <= '9')
{
    if (this.Text.Contains(',') 
        && this.SelectionLength == 0
        && this.SelectionStart > this.Text.IndexOf(',')
        && this.Text.Length - this.Text.IndexOf(',') > 2)
    {
        e.Handled = true;
    }

    return;
}

请不要像47那样使用幻数,让我们使用字符。我们应该允许这些字符:

  • '0'..'9' 范围(数字)
  • 用于tabbackspace等space' '的控制字符
  • ','(逗号)作为小数点分隔符

所有其他角色都应该被禁止。

代码:

private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
    char number = e.KeyChar;
    TextBox box = sender as TextBox;

    if (number >= '0' && number <= '9' || number < ' ')
        return; // numbers as well as backspaces, tabs: business as usual
    else if (number == ',') {  
        // We don't want to allow several commas, right?
        int p = box.Text.IndexOf(',');

        // So if we have a comma already...
        if (p >= 0) { 
            // ... we don't add another one
            e.Handled = true;

            // but place caret after the comma position
            box.SelectionStart = p + 1;
            box.SelectionLength = 0;  
        }  
        else if (box.SelectionStart == 0) {
            // if we don't have comma and we try to add comma at the 1st position 
            e.Handled = true;

            // let's add it as "0,"
            box.Text = "0," + box.Text.Substring(box.SelectionLength);
            box.SelectionStart = 2;
       } 
    }
    else  
        e.Handled = true; // all the other characters (like '+', 'p') are banned
}

请注意,有可能将粘贴不正确的值(比如"bla-bla-bla")到TbSalary TextBox;为了防止它,您可以使用 TextChanged 事件:

private void TbSalary_TextChanged(object sender, EventArgs e) {
  TextBox box = sender as TextBox;

  StringBuilder sb = new StringBuilder();

  bool hasComma = false;

  foreach (var c in box.Text)
    if (c >= '0' && c <= '9')
      sb.Append(c);
    else if (c == ',' && !hasComma) {
      hasComma = true;

      if (sb.Length <= 0) // we don't start from comma
        sb.Append('0');

      sb.Append(c);
    }

  string text = sb.ToString();

  if (!text.Equals(box.Text))
    box.Text = text;
}