c31983
c31983

Reputation: 449

Capture key strokes from any child control at the parent level

I have a WinForm control that has many child controls. The parent control will never have focus. I want to handle at the parent level certain key stroke combinations that occur at the child level. Below is a simple example of what I am trying to accomplish. If ChildB (or some control within ChildB) has focus, pressing Ctrl+A should remove ChildB from view and add ChildA.

public partial class ParentControl : UserControl
{
    ChildControl ChildA = new ChildControl();
    ChildControl ChildB = new ChildControl();
    ChildControl ChildC = new ChildControl();

    public ParentControl()
    {
        InitializeComponent();
        Controls.Add(ChildA);
    }

    private void CapturedFromCildControl(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.A)
        {
            Controls.Clear();
            Controls.Add(ChildA);
        }
        if (e.Control && e.KeyCode == Keys.B)
        {
            Controls.Clear();
            Controls.Add(ChildB);
        }
        if (e.Control && e.KeyCode == Keys.C)
        {
            Controls.Clear();
            Controls.Add(ChildC);
        }
    }
}

Upvotes: 3

Views: 1187

Answers (1)

rene
rene

Reputation: 42444

You can have your form preview all keys. For that you set the property KeyPreview of your form (!) to true (the deault is false). When this property is true, the keypress events of all child windows will first pass through the Form KeyEvent handlers.

You can then subscribe to those events from your ParentControl by using the ParentForm reference. The Load event of the ParentControl should look like this:

private void ParentControl_Load(object sender, EventArgs e)
{
    this.Controls.Add(new ChildControl1());
    this.ParentForm.KeyDown += CapturedFromCildControl;
}

During testing you'll notice that the sender will be the reference to the Form, not the ChildControl that captured the keypress. That doesn't look like an issue in your use-case but it is better to know upfront.

Upvotes: 2

Related Questions