为什么 KeyPressEventArgs 的 e.Handled 在 KeyPressEventArgs C# 中什么都不做?

Why KeyPressEventArgs's e.Handled does nothing in KeyPressEventArgs C#?

这段代码(通过互联网找到)似乎什么也没做。如何防止 TextBox

中出现非数字字符
private void textBox1_KeyPress( object sender, KeyPressEventArgs e )
{ 
   if( !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) )  
      e.Handled = true;
}

e.Handled的实际目的是什么?需要解释。

查看 MSDN: KeyEventArgs.Handled Property:

true to bypass the control's default handling; otherwise, false to also pass the event along to the default control handler.

你要的是SuppressKeyPress

e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);

另一种防止非数字字符的方法是尝试在

上使用正则表达式
private void textBox1_TextChanged(object sender, EventArgs e)
{
     if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
     {
          MessageBox.Show("Non numeric character detected.");
          textBox1.Text.Remove(textBox1.Text.Length - 1);
      }
}

你也可以参考这个MSDN forum:

The .Handled property is used to notify base classes whether or not the event has been handled or whether they need to address it. It doesn't communicate that a keystroke has been handled between keydown/keyup & keypress. It also works with forms with KeyPreview enabled, but only from the context of Form.KeyPress events. If you have a Form.KeyPress event that sets the .Handled, the control's event will be ignored. The give-away there is that KeyDown events deal with a KeyEventArgs where KeyPress events deal with KeyPressEventArgs.

The .SuppressKeyPress was probably added just for this reason, so KeyDown events could override KeyPress events.

和textBox1_KeyDown

 e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);

  if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                if (e.KeyCode != Keys.Back)
                {
                    nonnumberenter = true;
                    string abc = "Please enter numbers only.";
                    DialogResult result1 = MessageBox.Show(abc.ToString(), "Validate numbers", MessageBoxButtons.OK);
                }
            }
        }
        if (Control.ModifierKeys == Keys.Shift)
        {
            nonnumberenter = true;
            string abc = "Please enter numbers only.";
            DialogResult result1 = MessageBox.Show(abc.ToString(), "Validate numbers", MessageBoxButtons.OK);

        }

如果你想阻止 TextBox 中的非数字字符,那么只需 1 行就足以处理事件

e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);