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

北慕城南 提交于 2019-12-22 04:24:16

问题


This:

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:

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'"

So how can I accomplish this?


回答1:


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

see this: KeyPressEventArgs.KeyChar




回答2:


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




回答3:


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("-", "");
             }
        }
 }


来源:https://stackoverflow.com/questions/10288939/how-can-i-determine-if-the-backspace-has-been-pressed-in-the-keypress-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!