barlop
barlop

Reputation: 13820

c# winforms - How can I get the child form in front of parent form without making the parent one invisible?

This question is not a duplicate of Win Form in front of parent form

because the author of that one didn't seem to mind if the parent form was hidden, and the answers suggesting ShowDialog() hide the parent. I don't want the parent form hidden.

I have the following code in form_load

    private void Form1_Load(object sender, EventArgs e)
    {
        var childform = new Form();           
        childform.Show();
        childform.BringToFront();           
        childform.Activate();
    }

Yet it won't show the child in front of the parent. It shows this, as you can see, it's showing the parent form in front and the child behind, rather than the other way around which I want.

enter image description here

I've read of using childform.ShowDialog() but I don't want that because that would make the parent invisible while the child form shows. I want both visible.

I've read that BringToFront won't work 'cos it's for controls not forms, and to use Activate, but as you can see i've tried Activate and it isn't working either.

Upvotes: 0

Views: 3986

Answers (5)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

Try your code in the form's Shown event. That way the second form is shown after the main form and should thus become active.

Upvotes: 2

Tommy
Tommy

Reputation: 3134

Simply move the action to Shown event. You can remove both BringToFront and Activiate.

private void Form1_Shown(object sender, EventArgs e)
{
    var childform = new Form();
    childform.Show();
}

It is because when Load event is called, the form is yet shown.

As a result, your sequence becomes undesirably:

  1. Parent Load > Call Child
  2. Child Load
  3. Child Shown
  4. Parent Shown

Therefore, your parent is shown later and thus anyway is upper.

By using Shown event, the issue solved.

  1. Parent Load
  2. Parent Shown > Call Child
  3. Child Load
  4. Child Shown

Upvotes: 2

Shameel
Shameel

Reputation: 802

Form.Show() method has an overload that taken in an argument that specifies the parent of the form. Th child form is always shown above the parent form.

childForm.Show(this); //this is the parent form

Upvotes: 3

BlueMonkMN
BlueMonkMN

Reputation: 25601

Just include this as a parameter to the Show method.

var childform = new Form();
childform.Show(this);

Upvotes: 1

user1845593
user1845593

Reputation: 1844

try this after InitializeComponent():

this.Activated += (s, e) => ((Form)s).SendToBack();

where "this" is the parent form, so I'm casting "s" to Form

Upvotes: 0

Related Questions