0

I have got some controls on the Panel and I am trying to delete them using "Delete" button. I handled KeyPress Event as mentioned in How to get Keypress event in Windows Panel control in C# and I am getting Event for buttons (A-Z and 1-9) pressed, but not for the Delete, Control/Alt/ Shift or F1, F2.... buttons.

Do we need to do something special for handling these buttons?

Community
  • 1
  • 1
Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • Only controls that have the *focus* get keystrokes. And Panel does not like to get the focus. It does not show that it has the focus and you cannot tab to it, note that it doesn't have a TabIndex property. It is a container control, whatever is inside the panel gets the focus. Why you want to do this is entirely unclear. Don't use Panel. – Hans Passant Oct 05 '15 at 11:32
  • @Hans, I am using a Panel for drawing some controls on it. So what basically happens is user can draw any shapes (rectangle, Triangle etc) using mouse clicks. Now what I wanted is user can delete any selected Shape using "Delete" button. Something similar like Power Point slide and I user Panel as the container for the shapes. – Pankaj Oct 05 '15 at 13:48

1 Answers1

2

Try like this:

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

Also you need to set KeyPreview on.

You can also refer Keyboard.Modifiers Property

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • @Pankaj, [`KeyDown`](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx) (read corresponding mdsn page for important details) is the first event to mention, but sometimes you may want `KeyUp` – Sinatr Oct 05 '15 at 11:12
  • @Rahul Tripathi, Thanks . It is working now. I got more explanation from here http://stackoverflow.com/questions/8188328/c-sharp-keypress-doesnt-capture-delete-key. – Pankaj Oct 05 '15 at 11:15