Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
thuaso Avatar asked May 23 '10 21:05

thuaso


3 Answers

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

like image 70
ChrisF Avatar answered Sep 18 '22 09:09

ChrisF


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

            <ListView.InputBindings>
                <KeyBinding Command="{Binding COMMANDTORUN}"
                            Key="KEYHERE" />
            </ListView.InputBindings>
like image 24
Eric Avatar answered Sep 20 '22 09:09

Eric


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
            }
        }
    }
like image 27
Kyriakos Xatzisavvas Avatar answered Sep 20 '22 09:09

Kyriakos Xatzisavvas