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);
}
}