thuaso
thuaso

Reputation: 1095

How to capture delete key press in C#?

I want to capture delete key presses and do nothing when the key is pressed. How can I do that in WPF and Windows Forms?

Upvotes: 11

Views: 55923

Answers (5)

Kyriakos Xatzisavvas
Kyriakos Xatzisavvas

Reputation: 304

I tried all the stuff mentioned above but nothing worked for me, so im posting what i actually did and worked, in the hopes of helping others with the same problem as me:

In the code-behind of the xaml file, add an event handler in the constructor:

using System;
using System.Windows;
using System.Windows.Input;
public partial class NewView : UserControl
    {
    public NewView()
        {
            this.RemoveHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown)); 
            // im not sure if the above line is needed (or if the GC takes care of it
            // anyway) , im adding it just to be safe  
            this.AddHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown), true);
            InitializeComponent();
        }
     //....
      private void NewView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                //your logic
            }
        }
    }

Upvotes: 1

Johnny
Johnny

Reputation: 1575

Simply check the key_press or Key_Down event handler on the specific control and check like for WPF:

if (e.Key == Key.Delete)
{
   e.Handle = false;
}

For Windows Forms:

if (e.KeyCode == Keys.Delete)
{
   e.Handled = false;
}

Upvotes: 2

Eric
Eric

Reputation: 419

When using MVVM with WPF you can capture keypressed in XAML using Input Bindings.

            <ListView.InputBindings>
                <KeyBinding Command="{Binding COMMANDTORUN}"
                            Key="KEYHERE" />
            </ListView.InputBindings>

Upvotes: 31

ChrisF
ChrisF

Reputation: 137148

For WPF add a KeyDown handler:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        MessageBox.Show("delete pressed");
        e.Handled = true;
    }
}

Which is almost the same as for WinForms:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        MessageBox.Show("delete pressed");
        e.Handled = true;
    }
}

And don't forget to turn KeyPreview on.

If you want to prevent the keys default action being performed set e.Handled = true as shown above. It's the same in WinForms and WPF

Upvotes: 18

I don't know about WPF, but try the KeyDown event instead of the KeyPress event for Winforms.

See the MSDN article on Control.KeyPress, specifically the phrase "The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events."

Upvotes: 3

Related Questions