Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
    }
}
like image 391
c31983 Avatar asked Jan 24 '26 18:01

c31983


1 Answers

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.

like image 76
rene Avatar answered Jan 26 '26 10:01

rene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!