开发者

Cancel Key press event

开发者 https://www.devze.com 2022-12-25 17:42 出处:网络
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 event, I know there are other ways suc

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 event, I know there are other ways such as expression to match the string value, but I want to n开发者_JS百科ot assign invalid value to the textbox.

if (( value >0 a&&(value <=9)) then 
    assigned
else 
    return


Use the Handled Property

e.Handled = true;

Example from MSDN: link

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}


You may use keypress event as below. use e.Handled to true to cancel user input

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar)) e.Handled = true;
    }


Create a string with the characters you what to allow the user to enter.

Use KeyDown or KeyUp to handle Special keys

private void tbN1_KeyPress(object sender, KeyPressEventArgs e)
{
    String sKeys = "1234567890ABCDEF";
    if (!sKeys.Contains(e.KeyChar.ToString().ToUpper()))
        e.Handled = true;
}


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;
}


For WPF, use the PreviewTextInput event with code like:

// Filter out non-numeric keys.
private void MyApp_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
String sKeys = "1234567890";
if (!sKeys.Contains(e.Text))
    e.Handled = true;
}


You could use MaskedTextBox and force it to be integer only.


You can inherit from TextBox and then:

Protected Overrides Sub OnTextInput(ByVal e As System.Windows.Input.TextCompositionEventArgs)

        Dim newChar As Char = Convert.ToChar(e.Text)
        If Not [Char].IsDigit(newChar) Then e.Handled = True

End Sub

C# version

protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e)
{    
    char newChar = Convert.ToChar(e.Text);        
    if (!Char.IsDigit(newChar)) e.Handled = true; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号