C# 如何确定 KeyPress 事件中是否按下了退格键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10288939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:11:58  来源:igfitidea点击:

How can I determine if the Backspace has been pressed in the KeyPress event?

c#winformskeypresskeycode

提问by B. Clay Shannon

This:

这个:

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

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

...indicates that I should have access to e.KeyCode in the KeyPress event, but I don't seem to. I'm trying to allow only 1,2,3, and backspace:

...表示我应该可以在 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; 
  }
}

...but "e." does not show a "KeyCode" value like the example shows, and trying KeyChar with Keys.Back scolds me with, "Operator '!=' cannot be applied to operands of type 'char' and 'System.Windows.Forms.Keys'"

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

So how can I accomplish this?

那么我怎样才能做到这一点呢?

采纳答案by jorgehmv

try comparing e.KeyChar != (char)Keys.Back, you should cast it to char since Keys is an enumeration

尝试比较e.KeyChar != (char)Keys.Back,您应该将其转换为 char 因为 Keys 是一个枚举

see this: KeyPressEventArgs.KeyChar

看到这个:KeyPressEventArgs.KeyChar

回答by Neil Barnwell

I'm pretty sure I've only ever solved this by using the KeyDownevent instead; it has different event arguments.

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

回答by ankur goel

Try to put a condition like this:

尝试设置这样的条件:

Code :

代码 :

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