Prachi
Prachi

Reputation:

Disable backspace in wpf

I am working in a WPF application, using C#.net I want to know, is there any way to disable Backspace button on a particular xaml page. I want to prevent user from using the Backspace button on this particular xaml page. Even if the user presses the Backspace button, no effect should take place.

Thanks

Upvotes: 11

Views: 7862

Answers (3)

Ben
Ben

Reputation: 3391

So I preferred the approach by sipwiz because I did not want to disable all keyboard shortcut (I still want to use ALT-Left etc just not the Backspace).

For me using a WPF NavigationWindow, overriding the OnKeyDown method did not work at all, the window still navigated back when I pressed the Backspace key. Overriding the OnPreviewKeyDown did seem to work to start with but then I ran into problems when I needed the Backspace key to work with textboxes.

So I took what I learned from the approach by Ed Andersen and I added the following code to my NavigationWindow constructor:

KeyGesture backKeyGesture = null;
foreach(var gesture in NavigationCommands.BrowseBack.InputGestures)
{
    KeyGesture keyGesture = gesture as KeyGesture;
    if((keyGesture != null) &&
       (keyGesture.Key == Key.Back) &&
       (keyGesture.Modifiers == ModifierKeys.None))
    {
        backKeyGesture = keyGesture;
    }
}

if (backKeyGesture != null)
{
    NavigationCommands.BrowseBack.InputGestures.Remove(backKeyGesture);
}

Upvotes: 1

Ed Andersen
Ed Andersen

Reputation: 1158

If you want to prevent backspace going back up the navigation history in a WPF Frame, including special "Back" hardware buttons, use:

NavigationCommands.BrowseBack.InputGestures.Clear();
NavigationCommands.BrowseForward.InputGestures.Clear();

Upvotes: 31

sipsorcery
sipsorcery

Reputation: 30714

You'll need to catch the onKeyDown event and set handled to true for backspace.

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

Upvotes: 7

Related Questions