Home > Software design >  WPF TextBox - How to trap and deal with Backspace and Delete events
WPF TextBox - How to trap and deal with Backspace and Delete events

Time:03-07

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;
                       
                    }
                }
            }
        }

CodePudding user response:

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 Form1()
{
   InitializeComponent();
   MyTextBox.KeyDown  = new KeyEventHandler(TextBox_KeyDownHandler);
}
  • Related