繁体   English   中英

在 MDI Child 中心显示对话框

[英]Display dialog box in center of MDI Child

免责声明:我知道已经为类似问题提供了答案,但是这些似乎对我不起作用。

我有一个应用程序,它使用带有 MDIClient 的主窗体; 我想显示一个允许用户输入值的对话框; 此对话框将显示在调用该对话框的 MDIChild 窗体的中心。

我已经看过以下解决方案:

C# - 在其父级的中心显示对话框

但是,除非与我的解决方案存在与应用程序相关的差异,否则这似乎存在一些基本问题。

建议通过以下方式实现这一目标:

private void OpenForm(Form parent)
{
    FormLoading frm = new FormLoading();
    frm.Parent = parent;
    frm.StartPosition = FormStartPosition.CenterParent;
    frm.ShowDialog();
}

然而,这有以下问题:

当我尝试实现这一点时,在单步执行代码时,只要它碰到设置表单父级的行,就会发生以下异常:

Top-level control cannot be added to a control.

NB 除非所有 Forms 初始化的 TopLevel 值为true ,否则这个值似乎没有在任何地方设置!

可以,然后呢; 我们将 TopLevel 设置为false以允许将父窗体设置为对话框的父窗体。 假设我这样做,当它到达ShowDialog()行时:

Form that is not a top-level form cannot be displayed as a modal dialog box. Remove the form from any parent form before calling showDialog.

这就是我的泥潭; 对话框表单似乎不需要是顶级表单才能拥有父级,但同时需要是顶级表单,以便它可以显示为对话框......

最后一点,我认为我不应该设置我想要作为对话框的表单的“StartPosition”,因为这已经在表单的InitializeComponent()部分中设置了; 尽管如此,我已经尝试在函数中明确设置它并且没有任何区别。

您可以手动定位对话框表单:

    private void invokeDialogButton_Click(object sender, EventArgs e)
    {
        var dialogForm = new DialogForm();
        dialogForm.StartPosition = FormStartPosition.Manual;

        //Get the actual position of the MDI Parent form in screen coords
        Point screenLocation = Parent.PointToScreen(Parent.Location);

        //Adjust for position of the MDI Child form in screen coords
        screenLocation.X += Location.X;
        screenLocation.Y += Location.Y;

        dialogForm.Location = new Point(screenLocation.X + (Width - dialogForm.Width) / 2, 
                                        screenLocation.Y + (Height - dialogForm.Height) / 2);

        dialogForm.ShowDialog(this);
    }

在我的 Github 页面(Visual Studio 2015 社区版项目)上查看这个工作示例项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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