tags:

views:

305

answers:

4

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
A: 

For Windows Forms:

  1. Add a MenuStrip
  2. Add a new MenuItem and assign the shortcut for delete
  3. Implement the MenuItem event
  4. Set the MenuStrip or MenuItem visibility to false

It will override any event on the form when you press delete.

BrunoLM
That's exceptionally hacky.
Will Vousden
Isn't everything exceptionally hacky? ;-)
Shaharyar
+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
Thanks for reply. How can I prevent Delete action?
thuaso
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