开发者

How do I get the KeyDown event to fire in a custom container control?

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
开发者_JS百科{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete)
        {
            MessageBox.Show("How do I get here?");
            e.Handled = true;
        }

        base.OnKeyDown(e);
    }
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜