1

我有一个 MDI 表单,里面有很多控件,比如按钮、图像、标签、下拉列表等。我已经将表单属性设置为 isMDIContainer=true。当我单击表单内的按钮时,将在父级内打开另一个表单。现在它的打开,但不幸的是它在所有控件后面打开。如何使子窗体在主窗体的所有控件前面打开?

    Form2 childForm = new Form2();            
    childForm.MdiParent = this;
    childForm.Activate();          
    childForm.Show();
4

2 回答 2

2

通常我们不会将任何子控件添加到Mdi Form. 当 aForm用作 a时Mdi Form,它应该包含的唯一子级是MdiClient。这MdiClient将包含您的child forms. 所有控件都应放在Child forms. 但是,如果您愿意,我们仍然可以使其工作

MdiClienta中包含一个默认值Mdi Form。我们可以在Controls集合中找到它Mdi Form。它的类型MdiClient。这将被您的所有其他控件所覆盖,Mdi Form这就是为什么Child forms默认情况下不能将您置于首位的原因。为了解决这个问题,我们只需访问MdiClientand 调用BringToFont(),只要没有任何Child form存在Visible,我们就会调用SendToBack()MdiClient显示您的其他控件(按钮、图像、标签、下拉列表等)。这是供您测试的代码:

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);         
    }     
}
于 2013-08-26T03:14:17.227 回答
-1

处理Shown事件并调用this.BringToFront();.

于 2013-08-26T02:12:14.503 回答