views:

342

answers:

2

I have a custom container control (deriving from FlowLayoutPanel) which contains zero or more child controls dragged there by the user. When a child control is clicked, it is "selected." (It is drawn with a colored border and options are available for altering its properties.)

I would like to handle the Delete key so that, if the user is currently working in the container control (clicked within the control or on a child control, for instance) the currently selected control (if there is one) is deleted.

I already have the delete functionality working using a right-click context menu on the child items. My problem is handling the Delete key. I cannot figure out how to get the KeyDown event to raise within my container control. I know it has something to do with focus, so that Control.Select() (or its equivalent) must be called, but what is the best way to go about this? Where does this focus logic reside? Or is there a better way?

I do not want to handle the KeyDown event in the form and then sniff out where the focus is. This is a reuseable container control and I want the logic to reside there.

What do I have to do to get the KeyDown event to fire on a custom control?

public class MyContainer : FlowLayoutPanel
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete)
        {
            MessageBox.Show("How do I get here?");
            e.Handled = true;
        }

        base.OnKeyDown(e);
    }
}
+1  A: 

Is it possible that the items dragged into the container are receiving the event?

Perhaps after an item is drug into your container, you need to manually set the focus to the container.

taylonr
Thanks for the response. This led me to a solution. The child controls were also unable to receive focus, so there was no way for anything to say "Hey! I have the focus now!" within my entire control heirarchy. I just did a Control.Select() in the OnMouseDown method override for my child controls. Then I could handle the OnKeyDown event right there. If I had to handle it in the container, I could do what you suggest or override the ProcessKeyPreview method, the latter of which looked like a pain. :)
Dave
+2  A: 

The KeyDown event is listed as unmeaningful for the FlowLayoutPanel control on MSDN. Suggest the PreviewKeyDown event as an alternative.

JonathanK
Thanks for the suggestion. The PreviewKeyDown event was also not firing in my scenario. As I kept playing with it, I realized my question above may have been too simplistic. My container control is hosted within a UserControl, and that seems to complicate life even more.
Dave