[SOLVED] WPF TextBox – How to trap and deal with Backspace and Delete events

Issue

I am trying to warn the user when they select and delete text in a wpf textbox.
I am able to trap the delete event using the previewkeydown event, but its is canceling out the delete event. Even when you press ok in the code below – deletion does not happen. I am missing something …

private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Delete)
            {
                var textbox = (TextBox)sender;
                if (textbox.SelectionLength > 1)
                {
                    var result = MessageBox.Show("Delete selected?", "MyApp", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        e.Handled = true;
                       
                    }
                }
            }
        }

Solution

This does not seem to be the proper usage of the PreviewKeyDown event handler. That handler seems to be meant to redirect non-standard input key events to do custom behavior. The delete key is not considered non-standard/special.

You’ve got the right idea with your current code otherwise, but now you just need to actually delete the text in the textbox.

private void TextBox_KeyDownHandler(object sender, KeyEventArgs e)
{
    switch(e.KeyCode)
    {
       case Keys.Delete:
            if (sender is TextBox tb)
            {
                if(tb.SelectionLength > 1 && MessageBox.Show("Delete?", "MyApp", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    tb.SelectedText = "";
                }
            }
            e.Handled = true;
            break;
    }
}

Lastly, make sure you’re actually subscribing your handlers

public MainWindow()
{
   InitializeComponent();
   MyTextBox.KeyDown += new KeyEventHandler(TextBox_KeyDownHandler);
}

Answered By – Ryan R

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *