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?
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
When using MVVM with WPF you can capture keypressed in XAML using Input Bindings.
<ListView.InputBindings>
<KeyBinding Command="{Binding COMMANDTORUN}"
Key="KEYHERE" />
</ListView.InputBindings>
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With