How to determine if Backspace was clicked in a KeyPress event?

It:

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 it seems to me not. I am trying to resolve 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." doesn’t show the value of "KeyCode", as shown in the example, and trying to KeyChar with Keys.Back scolds me, "Operator"! = "cannot be applied to operands of type" char "and" System.Windows.Forms. Keys "

So how can I do this?

+6
source share
3 answers

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

see this: KeyPressEventArgs.KeyChar

+14
source

I am sure that I only solved this using the KeyDown event; It has different event arguments.

+1
source

Try setting this condition:

The code:

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

Source: https://habr.com/ru/post/913989/


All Articles