Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

How do I show a new MDI child form without losing focus?

$
0
0

I have an application in which the main form has some controls placed on it and it is a MDI parent.  I want to create and show a new MDI child window without the focus changing from the parent window's selected control.  Calling child.Show() seems to switch the focus to the MDI child.

Is there some way to show a new MDI child form without the focus changing to it?

I tried overriding ShowWithoutActivation but that appears to do nothing in the case of an MDI child form.  I also tried to use the user.dll function ShowWindow(handle, 4) to try to show the window manually without activating it and that fails. If I store the focus before Show() then restore it after, it is going to make the focus flicker in an undesirable way,  Likewise, I could prevent the window from gaining focus by setting Enabled = false before Show(), but it will make my controls dim out then undim when Enabled is set back to true after Show() which is also ugly.

Here's some sample code that illustrates the basic problem.  You can start the application and press space or enter and it will activate the main form's button which is in focus, but it makes the button lose focus so you can't press space repeatedly to spawn multiple windows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

    public class MDIChild : Form
    {
        public MDIChild()
        {
            this.AutoSize = true;
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;

            Label label = new Label();
            label.Text = "I stole the focus.";
            Controls.Add(label);
        }
    }

    public class Form1 : Form
    {
        Button button1;

        public Form1()
        {
            this.Text = "Form1";
            this.IsMdiContainer = true;

            button1 = new Button();
            button1.Dock = DockStyle.Top;
            button1.Text = "New MDI Child (Space bar activates while in focus)";
            button1.Click += new EventHandler(MakeChild_Click);
            Controls.Add(button1);
        }

        void  MakeChild_Click(object sender, EventArgs e)
        {
            MDIChild child = new MDIChild();
            child.MdiParent = this;
            child.Show();
        }
    }
}




Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>