Prevent backspace in richtextbox using C# .net

1.6k Views Asked by At

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

2

There are 2 best solutions below

2
On

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.

7
On

Try this:

if (e.KeyChar == '\b')