【问题标题】:How can I determine if the Backspace has been pressed in the KeyPress event?如何确定是否在 KeyPress 事件中按下了 Backspace?
【发布时间】:2012-05-04 13:26:37
【问题描述】:

这个:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

...表示我应该可以在 KeyPress 事件中访问 e.KeyCode,但我似乎没有。我试图只允许 1、2、3 和退格:

private void textBoxQH1_KeyPress(object sender, KeyPressEventArgs e) {
  if ((e.KeyChar != '1') &&
      (e.KeyChar != '2') &&
      (e.KeyChar != '3') &&
      (e.KeyChar != (Keys.Back))) {
    e.Handled = true; 
  }
}

...但是“e”。没有像示例所示那样显示“KeyCode”值,并且尝试使用 KeyChar 和 Keys.Back 责骂我,“运算符'!='不能应用于'char'和'System.Windows.Forms.Keys'类型的操作数"

那我该怎么做呢?

【问题讨论】:

  • c#???嗯,我不确定,但也许:(e.KeyChar != (char)8)?

标签: c# winforms keypress keycode


【解决方案1】:

尝试比较e.KeyChar != (char)Keys.Back,你应该把它转换成char,因为Keys是一个枚举

看到这个:KeyPressEventArgs.KeyChar

【讨论】:

    【解决方案2】:

    我很确定我只是通过使用KeyDown 事件解决了这个问题;它有不同的事件参数。

    【讨论】:

      【解决方案3】:

      试着提出这样的条件:

      代码:

       if (e.KeyCode == (Keys.Back))
       {
              if(textBox1.Text.Length >=3)
              {
                   if (textBox1.Text.Contains("-"))
                   {
                       textBox1.Text.Replace("-", "");
                   }
              }
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多