更新时间:2023-12-06 11:03:16
通常我们不向Mdi Form
添加任何子控件.当 Form
用作 Mdi Form
时,它应该包含的唯一子项是 MdiClient
.MdiClient
将包含您的 子表单
.所有的控件都应该放在子窗体
上.但是,如果您愿意,我们仍然可以使其正常运行
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
Mdi 表单
中包含一个默认的MdiClient
.我们可以在 Mdi Form
的 Controls
集合中找到它.它是 MdiClient
的类型.这将由您的 Mdi 表单
的所有其他控件覆盖,这就是默认情况下您的 子表单
不能置于顶部的原因.要解决它,我们只需访问 MdiClient
并调用 BringToFont()
并且只要没有任何 Child form
成为 >Visible
,我们将在 MdiClient
上调用 SendToBack()
来显示您的其他控件(按钮、图像、标签、下拉菜单等).以下是供您测试的代码:
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);
}
}