Отмена события нажатия клавиши - PullRequest
7 голосов
/ 07 апреля 2010

Как я могу вернуть ключ ?, то есть, если я хочу разрешить только целочисленные значения в текстовом поле, как я могу не позволить пользователю не вводить нецелые числа, касающиеся события KeyPress, я знаюдругие способы, такие как выражение для соответствия строковому значению, но я не хочу присваивать недопустимое значение текстовому полю.

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

Ответы [ 7 ]

18 голосов
/ 07 апреля 2010

Использовать обработанное свойство

e.Handled = true;

Пример из MSDN: ссылка

// 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;
    }
}
7 голосов
/ 16 июля 2014

Создайте строку с символами, которые вы хотите ввести пользователю.

Используйте KeyDown или KeyUp для обработки специальных клавиш

private void tbN1_KeyPress(object sender, KeyPressEventArgs e)
{
    String sKeys = "1234567890ABCDEF";
    if (!sKeys.Contains(e.KeyChar.ToString().ToUpper()))
        e.Handled = true;
}
7 голосов
/ 07 октября 2012

Вы можете использовать событие нажатия клавиши, как показано ниже. используйте e.Handled для true, чтобы отменить ввод пользователя

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar)) e.Handled = true;
    }
1 голос
/ 24 июля 2018

Для WPF используйте событие PreviewTextInput с кодом:

// Filter out non-numeric keys.
private void MyApp_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
String sKeys = "1234567890";
if (!sKeys.Contains(e.Text))
    e.Handled = true;
}
1 голос
/ 09 июня 2015

Технически это неправильно, так как вы пометили свой вопрос WPF.Но так как вы приняли другой ответ Windows Forms, я опубликую свое решение, которое работает для действительных чисел, а не целых чисел.Он также локализован, чтобы принимать только десятичный разделитель текущей локали.

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;
}
0 голосов
/ 07 апреля 2010

Вы можете наследовать от TextBox, а затем:

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 # версия

protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e)
{    
    char newChar = Convert.ToChar(e.Text);        
    if (!Char.IsDigit(newChar)) e.Handled = true; 
}
0 голосов
/ 07 апреля 2010

Вы можете использовать MaskedTextBox и сделать его целым числом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...