【问题标题】:Cancel Key press event取消按键事件
【发布时间】:2010-04-07 09:27:10
【问题描述】:

我怎样才能返回密钥?,意思是如果我想在文本框中只允许整数值,我怎么能不允许用户不输入非整数,关于 KeyPress 事件,我知道有其他方式如表达式来匹配字符串值,但我不想给文本框分配无效值。

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

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    使用 Handled 属性

    e.Handled = true;
    

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

    【讨论】:

      【解决方案2】:

      您可以使用如下按键事件。使用 e.Handled 为 true 取消用户输入

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

      【讨论】:

        【解决方案3】:

        使用您允许用户输入的字符创建一个字符串。

        使用KeyDownKeyUp 处理特殊键

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

        【讨论】:

          【解决方案4】:

          从技术上讲,这是错误的,因为您标记了您的问题 WPF。但是由于您接受了其他 Windows 窗体的答案,我将发布我的解决方案,该解决方案适用于实数而不是整数。它也被本地化为只接受当前语言环境的小数点分隔符。

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

          【讨论】:

            【解决方案5】:

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

            【讨论】:

              【解决方案6】:

              您可以使用 MaskedTextBox 并将其强制为仅整数。

              【讨论】:

              【解决方案7】:

              您可以从 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; 
              }
              

              【讨论】:

                猜你喜欢
                • 2012-10-25
                • 2016-08-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-03-07
                • 1970-01-01
                • 1970-01-01
                • 2020-08-04
                相关资源
                最近更新 更多