Search code examples
c#winformsmdi

Set focus to an mdi container after showing an mdi child


I'm trying to make a form that is an MDI container, and when I press a button on the numpad (1-9), a small form (that will be the form's MDI child) will appear in the relative location to the position of the digit in the numpad (5 is in the middle, 9 is top right), and then I want the focus of the program to return to the mdi container so you can press the button again.

I have a keypress event in my MDI container set up like this:

private void MdiClient_KeyPress(object sender, KeyPressEventArgs e)
        {
            int num;
            if (e.KeyChar >= '1' && e.KeyChar <= '9')
            {
                num = e.KeyChar - '0';
                PhysicalChild pc = new PhysicalChild();
                pc.MdiParent = this;
                pc.Show();
                pc.Location = new Point(num % 3 * Width / 2 - 50 * num, num / 3 * Height / 2 - 50 * num);
                pc.Size = new Size(50, 50);
                Focus();
            }
        }

The problem is it doesn't return the focus to the MDI container, not even if I click the mouse on the container area, I have to close the MDI child for it to receive more button presses.

What am I doing wrong and how should I fix it?

Thanks.


Solution

  • From what I've read, when there are MDI child forms, they will always have the focus. The MDI parent only gets the focus when there are no child forms that can hold the focus.

    But, from what I've read here about child windows, you can change the parent window property on the child to Null. That will decouple the child from the parent ... which ought to have the effect of making your MDI window childless again. (Disclaimer: I haven't actually tried this, so I don't know if it will solve your problem.)

    If that doesn't work, an MDI window may not be the best solution for your application. MDI windows are usually empty containers, except for a menu: they don't tend to have content of their own.