How to focus a control in an MDIParent when all child windows have closed?

Posted by Tim Gradwell on Stack Overflow See other posts from Stack Overflow or by Tim Gradwell
Published on 2010-06-06T13:16:52Z Indexed on 2010/06/06 13:22 UTC
Read the original article Hit count: 179

Filed under:
|

I have a control in my parent mdi form which I wish to be given the focus if all mdi children have closed. I've tried hooking into the child form's FormClosed event and setting the focus from there but when I test it, my control is not left with focus when I close the mdi child.

Can anyone tell me what I'm missing?

In the sample below, "first focus" gets hit and does its job correctly (if I comment out the first focus line, my tree does not get focus on startup, so it must be doing its job, right?) Unfortunately, even though "second focus" gets hit, my tree does not end up with the focus when I close the child window.


Sample

using System;
using System.Windows.Forms;

namespace mdiFocus
{
   class ParentForm : Form
   {
      public ParentForm()
      {
         IsMdiContainer = true;
         tree = new TreeView();
         tree.Nodes.Add("SomeNode");
         tree.Dock = DockStyle.Left;
         Controls.Add(tree);
      }
      protected override void OnShown(EventArgs e)
      {
         Form child = new Form();
         child.MdiParent = this;
         child.Show();
         child.FormClosed += new FormClosedEventHandler(child_FormClosed);
         tree.Focus(); // first focus works ok
      }
      void child_FormClosed(object sender, FormClosedEventArgs e)
      {
         tree.Focus(); // second focus doesn't seem to work, even though it is hit :(
      }
      TreeView tree;
   }

   static class Program
   {
      [STAThread]
      static void Main()
      {
         Application.Run(new ParentForm());
      }
   }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms