I want to capture delete key press and do nothing when key is pressed. How can I do that in WPF and Winforms?
A:
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."
LittleBobbyTables
2010-05-23 21:35:36
A:
For Windows Forms:
- Add a MenuStrip
- Add a new MenuItem and assign the shortcut for delete
- Implement the MenuItem event
- Set the MenuStrip or MenuItem visibility to false
It will override any event on the form when you press delete.
BrunoLM
2010-05-23 21:43:32
That's exceptionally hacky.
Will Vousden
2010-05-23 21:46:39
Isn't everything exceptionally hacky? ;-)
Shaharyar
2010-05-23 21:50:48
+3
A:
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
ChrisF
2010-05-23 21:49:10
A:
simply check the key_press
or Key_Down
event handler on specific control
and check like
for WPF
if(e.Key == Key.Delete)
{
e.Handle = false;
}
for winforms
if (e.KeyCode == Keys.Delete)
{
e.handle = false;
}
Johnny
2010-05-24 07:23:51