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

4

11

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?

Arsenic answered 23/4, 2012 at 22:1 Comment(1)
c#??? hum, I'm not sure but maybe: (e.KeyChar != (char)8) ?Deform
F
25

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

see this: KeyPressEventArgs.KeyChar

Folberth answered 23/4, 2012 at 22:7 Comment(0)
U
2

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

Unconquerable answered 23/4, 2012 at 22:6 Comment(0)
L
1

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("-", "");
             }
        }
 }
Limitative answered 22/9, 2016 at 5:7 Comment(1)
Thanks great help! Noticed KeyCode does not work, but it works wit KeyChar if (e.KeyChar == ((char)Keys.Back))Lunseth
L
0

I needed to add 0 back after deleting all the textbox content with backspace (if last keystroke is backspace condition is met), while still clearing the textbox upon Keypress and the texbox only contains zero (when first putting input in textbox, with the Form1.cs [Desigh] Properties Text set to 0):

    private void textBox14_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (textBox14.Text == "0")
            textBox14.Clear();

        if (e.KeyChar == ((char)Keys.Back))
        {
            if (textBox14.Text.Length <= 1)
            {
                textBox14.Text = "0";
            }
        }

        if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
        if (e.KeyChar == '+' || e.KeyChar == '-' || e.KeyChar == '.') return;
        if (!Char.IsControl(e.KeyChar))

        e.Handled = true;
    }
Lunseth answered 25/5 at 19:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.