2

I'm pulling my hair out over this one. Very simple windows forms program. I have a richtextbox and I want to prevent the backspace from doing anything in the richtextbox. Here is my code

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyChar == (char)Keys.Back)
     {
          e.handled = true;
     }
}

If I put a breakpoint at e.handled and I type a backspace it indeed breaks. However the backspace still makes it to the richtextbox. So I have seen examples where PreviewKeyDown is used however NONE of those examples work! I tried

void richTextBox1.PreviewKeyDown(object sender, KeyPressEventArgs e)
{
     e.Handled = true;
}

However KeyPressEventArgs is not valid! If I use what Forms gives it's PreviewKeyDownEventArgs and the is no e.Handles available. So how does one do this?

Thanks

Tom
  • 527
  • 1
  • 8
  • 28

2 Answers2

5

Use the KeyDown event to cancel the backspace key press.

private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Back)
     {
          e.Handled = true;
     }
}

The MSDN page about the KeyPress event has the following comment:

Some controls will process certain key strokes on KeyDown. For example, RichTextBox processes the Enter key before KeyPress is called. In such cases, you cannot cancel the KeyPress event, and must cancel the key stroke from KeyDown instead.

dodald
  • 603
  • 3
  • 8
0

Try this:

if (e.KeyChar == '\b')
phantom
  • 1,457
  • 7
  • 15
  • 1
    `KeyChar` is a `char`, not a `string`. Fixed that for you. – gunr2171 Oct 31 '14 at 16:31
  • @gunr2171 Whoops thanks! Been doing too much python :D – phantom Oct 31 '14 at 16:33
  • I could not get this particular solution to work. The KeyPress event is issued, and it does have the value '\b', but setting Handled to true has no effect (The backspace is still processed). I suspect this is one of the keys that is handled on KeyDown. – dodald Oct 31 '14 at 16:57
  • Well I have solved it. It turns out you have to use KeyDown and then check KeyChar and if a backspace do a e.Handled = true; However as I didn't mention, I also wanted the actual character in other cases. So you also have to do KeyPress which always fires after KeyDown and passes the keychar even if you issue the e.handled. – Tom Nov 01 '14 at 19:50
  • 1
    @Tom Fantastic! To assist future visitors from google, why don't you create an answer showing the code you used and accept it as the answer? – phantom Nov 01 '14 at 19:55
  • I tried, but it wouldn't let me! – Tom Nov 11 '14 at 03:39
  • @Tom Click the checkmark underneath the voting options! – phantom Nov 11 '14 at 03:57