Frage

I have a MDI form with many controls inside it like button,images,label,dropdown etc.I have made the form property isMDIContainer=true.When i click on a button inside the form another form is to be opened inside the parent.Now its opening,but unfortunately its opening behind all the controls.How to make the child form open infront of all the controls of main form?

    Form2 childForm = new Form2();            
    childForm.MdiParent = this;
    childForm.Activate();          
    childForm.Show();
War es hilfreich?

Lösung

Normally we don't add any child controls to a Mdi Form. When a Form is used as an Mdi Form, the only child it should contain is MdiClient. That MdiClient will contain your child forms. All the controls should be placed on the Child forms. However if you want so, we can still make it work

There is a default MdiClient contained in a Mdi Form. We can find it in the Controls collection of the Mdi Form. It's type of MdiClient. This will be covered by all other controls of your Mdi Form and that's why your Child forms can't be brought on top by default. To solve it, simply we have to access to the MdiClient and call BringToFont() and whenever there isn't any Child form being Visible, we will call SendToBack() on the MdiClient to show the other controls of yours (button,images,label,dropdown etc). Here is the code for you to test:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        IsMdiContainer = true;
        //Find the MdiClient and hold it by a variable
        client = Controls.OfType<MdiClient>().First();
        //This will check whenever client gets focused and there aren't any
        //child forms opened, Send the client to back so that the other controls can be shown back.
        client.GotFocus += (s, e) => {
            if (!MdiChildren.Any(x => x.Visible)) client.SendToBack();
        };
    }
    MdiClient client;
    //This is used to show a child form
    //Note that we have to call client.BringToFront();
    private void ShowForm(Form childForm)
    {
        client.BringToFront();//This will make your child form shown on top.
        childForm.Show();            
    }
    //button1 is a button on your Form1 (Mdi container)
    //clicking it to show a child form and see it in action
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2 { MdiParent = this };
        ShowForm(f);         
    }     
}

Andere Tipps

Handle the Shown event and call this.BringToFront();.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top