【问题标题】:Keeping child form centered in MDI parent保持子窗体在 MDI 父窗体中居中
【发布时间】:2013-08-31 01:08:37
【问题描述】:

我创建了一个主窗体,它是一个 MDI 窗体,也是一个子窗体。

当我“最大化”或“恢复” MDI 表单时,如何使子表单保持在父 MDI 表单的中心?

【问题讨论】:

  • 如果最大化或最小化,你会如何居中?
  • @NhemAranas 您好,我已经编辑了您的问题以澄清问题所在。如果我在里面放了不是你想要的东西,请随意回滚更改或重新编辑。

标签: c# winforms visual-studio-2010 c#-4.0


【解决方案1】:

让我看看我的理解是否正确,您希望您的 MDI 应用程序在表单的中心打开您的子表单,然后无论您如何调整它的大小都将其保留在那里。 Mdi 界面对如何放置表单有自己的想法,第一步是让 Child 表单在其 load 事件中设置其位置,然后您可以使用 Parents Resize 事件将其保持在中心。这是一个使用 2 Forms 的示例,看看它是否是您想要的。

Form1 Mdi 父级

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Form2 frm2 = new Form2();
        frm2.MdiParent = this;
        frm2.Show();
    }

    protected override void OnResize(EventArgs e)
    {
        CenterForms();
        base.OnResize(e);
    }
    private void CenterForms()
    {
        foreach (var form in MdiChildren) //This will center all of the Child Forms
        {
            form.Left = (ClientRectangle.Width - form.Width) / 2;
            form.Top = (ClientRectangle.Height - form.Height) / 2;
        }

    }
}

Form2 Mdi Child

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Left = (MdiParent.ClientRectangle.Width - Width) / 2;
        Top = (MdiParent.ClientRectangle.Height - Height)/2;
    }
}

【讨论】:

    【解决方案2】:

    您只需将子窗体的起始位置设置在 Parent Like This 的中心

    你的孩子表格

    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
    

    【讨论】:

      【解决方案3】:

      您可以将子表单属性“StartPosition”设置为CenterParent

      在加载新表单时,添加此代码

      Form frm = new Form();
      frm.StartPosition = FormStartPosition.Manual;
      frm.Location = new Point(this.Location.X + (this.Width - frm.Width) / 2, this.Location.Y + (this.Height - frm.Height) / 2);
      frm.Show(this);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多