Cancel Key press event

后端 未结 7 2082
别那么骄傲
别那么骄傲 2021-01-05 07:37

How can I return the key?, mean if I want to allow only integer values in the textbox, how can I don\'t allow user to not enter non-integers, regarding, KeyPress

7条回答
  •  暖寄归人
    2021-01-05 08:21

    Technically this is wrong since you tagged your question WPF. But since you accepted the other Windows Forms answer, I'll post my solution which works for real numbers rather than integers. It's also localized to only accept the current locale's decimal separator.

    private void doubleTextBox_KeyPress (object sender, KeyPressEventArgs e)
    {
      var textBox = sender as TextBoxBase;
      if (textBox == null)
          return;
    
      // did the user press their locale's decimal separator?
      if (e.KeyChar.ToString() == CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
      {
          if (textBox.Text.Length == 0) // if empty, prefix the decimal with a 0
          {
              textBox.Text = "0" + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
              e.Handled = true;
              textBox.SelectionStart = textBox.TextLength;
          }
          // ignore extra decimal separators
          else if (textBox.Text.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
              e.Handled = true;
      }
      // allow backspaces, but no other non-numeric characters;
      // note that arrow keys, delete, home, end, etc. do not trigger KeyPress
      else if (e.KeyChar != '\b' && (e.KeyChar < '0' || e.KeyChar > '9'))
          e.Handled = true;
    }
    

提交回复
热议问题