Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 394
B. Clay Shannon-B. Crow Raven Avatar asked Apr 23 '12 22:04

B. Clay Shannon-B. Crow Raven


People also ask

How do you handle backspace in JavaScript?

You can capture a backspace key on the onkeydown event. Once you get the key of the pressed button, then match it with the Backspace key code. A Backspace key keycode it 8. Use keydown instead of keypress .

What is keypress event in JavaScript?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.


2 Answers

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

see this: KeyPressEventArgs.KeyChar

like image 141
jorgehmv Avatar answered Oct 12 '22 06:10

jorgehmv


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

like image 2
Neil Barnwell Avatar answered Oct 12 '22 06:10

Neil Barnwell