How to forbid backspace key in WPF
Asked Answered
M

2

7

How can I forbid the Backspace-Key as easy as possible in a WPF-Application?

The KeyDown-Event don't catch at the DEL and the Backspace-Key.

Thank you!

Marquettamarquette answered 15/10, 2010 at 10:14 Comment(0)
L
15

To handle Backspace or other pressed key in order to cancel it, try to use the "PreviewKeyDown" event handler.

In your Xaml, set the attribute PreviewKeyDown like this :

<TextBox PreviewKeyDown="textBox1_PreviewKeyDown" ...

and in your code, define the event handler like this :

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Back || e.Key == Key.Delete)
    {
        e.Handled = true;
    }
}

Hop that helps :)

Lemaceon answered 15/10, 2010 at 11:31 Comment(0)
H
0

Try overriding OnTextInput(...).

Then if(args.Text == "\b") should give you the backspace.

Hagbut answered 15/10, 2010 at 10:28 Comment(2)
That doesn't exists in .NET 4.0 for a WPF Application :-(Marquettamarquette
@Xarem, but it does. See msdn.microsoft.com/en-us/library/…. Are you not subclassing a Window class?Hagbut

© 2022 - 2024 — McMap. All rights reserved.