如何允许 ShowDialog MDI 子级在 MDI 窗体父级上?

How allows ShowDialog MDI children on MDI Form parent?

在 MDI 父窗体中(使用 属性 this.IsMdiContainer = true)我们不允许使用方法 ShowDialog() 显示任何子窗体;自动会抛出以下异常:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: 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.

有没有人找到解决这个问题的方法?

我在我的项目中实施的一个简单而干净的解决方案是使用回调函数(Action<T> 在 C# 中),当用户输入所需的输入时触发。

使用 ShowDialog 的示例:

private void cmdGetList_Click(object sender, EventArgs e)
{
    string strInput = "";

    frmInputBox frmDialog = new frmInputBox("User input:");

    if (frmDialog.ShowDialog() == DialogResult.OK)
        strInput = frmDialog.prpResult;
    else
        strInput = null;
}

输入框在MDI主窗体外

现在;使用 Show:

的解决方案
private void cmdGetList_Click(object sender, EventArgs e)
{
    getInput(this, (string strResult) =>
        {
            MessageBox.Show(strResult);
        });
}

private void getInput(Form frmParent, Action<string> callback)
{
    // CUSTOM INPUT BOX
    frmInputBox frmDialog = new frmInputBox("User input:");

    // EVENT TO DISPOSE THE FORM
    frmDialog.FormClosed += (object closeSender, FormClosedEventArgs closeE) =>
    {
        frmDialog.Dispose();
        frmDialog = null;
    };

    frmDialog.MdiParent = frmParent; // Previosuly I set => frmParent.IsMdiContainer = true;

    // frmDialog.ShowDialog(); <== WILL RAISE AN ERROR
    // INSTEAD OF:
    frmDialog.MdiParent = frmParent;

    frmDialog.FormClosing += (object sender, FormClosingEventArgs e) =>
    {
        if (frmDialog.DialogResult == DialogResult.OK)
            callback(frmDialog.prpResult);
        else
            callback(null);
    };

    frmDialog.Show();
}

输入框(或任何窗体将显示在MDI父窗体中):

诀窍是使用回调函数(C# 上的 Action)来管理用户输入的时间。

就是代码行多了,不过为了展示一个干净的项目,不值钱。