简体   繁体   中英

How to prevent a Windows Form from being sent to the back or how to keep it on a specific z-order

I'm encountering a strange problem with Form layout ordering (z-order). Lets say I've three Windows Forms; Form1, Form2 and Form3.

Form1 is launched as application's main form, and it has a button that opens Form2 as a Dialog (using ShowDialog() ). Form2 also has button that opens Form3 (but not as a Dialog, using Show() ). Once Form3 is opened, it jumps to the background (behind Form1) as soon as Form2 is clicked. I want to keep Form3 at-least above Form1 when Form2 is clicked, since it contains some options that assist working on Form2.

I Don't want to use Form3.TopMost = True; since it then keeps the Form3 on top of nearly everything even if you open or switch to any other application (eg Windows Explorer, Internet Browsers etc).

.BringToFront() also doesn't help. I've tried several combinations of some relevant Form events with Form.BringToFront() , Form.Activate() etc but all in vain. Any help would be appreciated.

Here is the code for reference:

Form1:

Form2 obj2 = new Form2();
private void button1_Click(object sender, EventArgs e)
{
    if (obj2 != null && obj2.Visible) { obj2.Focus(); return; }

    obj2 = new Form2();
    obj2.ShowDialog();
}

Form2:

Form3 obj3 = new Form3();
private void button1_Click(object sender, EventArgs e)
{
    if (obj3 != null && obj3.Visible) { obj3.Focus(); return; }

    obj3 = new Form3();
    obj3.Show();            
}

Try something like this, could help setting the parent.

Form3 obj3 = new Form3();
private void button1_Click(object sender, EventArgs e)
{
    if (obj3 != null && obj3.Visible) { obj3.Focus(); return; }

    obj3 = new Form3();
    obj3.Show(this);            
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM