Search code examples
c#winformsz-order

Window of another process comes between my two forms


I have a .Net winforms (C#) application with its main form (form A), and it opens different other forms as non-modal (so that user can work on either the main form or child forms independently)

In some cases, the child form (form B) opens another pop up form (form C). When this pop up is closed, another window from another application (e.g.chrome, outlook, VS) comes in between my main form and child form. Usually this other window is the one which was just underneath my main window.

Before closing the form, the z-order is: Outlook, Form A, Form B, Form C

After closing form c, the z-order changes to: Form A, Outlook, Form B

I didn't want to specifically BringToFront() my Form A, because there could be many instances of Form B at a given time, and I don't want to make my Form A over the Form B's.

Any idea what could cause this kind of behavior? Is there a way to make sure all my application's forms are above other windows?


Solution

  • You could make the child forms Owned by the form that opens them. This will maintain a relative z-order.

    public partial class FormA : Form
        {
    
        private void button1_Click(object sender, EventArgs e)
            {
            FormB f = new FormB();
            f.Show(this);
            }
        }
    

    public partial class FormB : Form
        {
    
        private void button1_Click(object sender, EventArgs e)
            {
            FormC f = new FormC();
            f.Show(this.Owner);
            }
        }
    

    This has the side effect that when a form's owner is closed/minimized, its owned forms also will close/minimize.