1

我有以下代码:

表格1

public partial class Form1 : Form
{
    Dialog dlg;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        dlg = new Dialog();
        dlg.Show(this);
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (dlg != null && !dlg.IsDisposed)
        {
            this.RemoveOwnedForm(dlg);
            dlg.Dispose();
        }
    }
}

对话

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

    private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        Hide();
    }
}

我需要在 form1 的“X”按钮上单击两次才能关闭它。有什么问题?

4

2 回答 2

1

I can't try it right now, but in the Dialog_FormClosing you could add this test

if(this.Owner != null)
{
    e.Cancel = true;
    Hide();
}

From MSDN docs on RemoveOwnedForm:

The form assigned to the owner form remains owned until the RemoveOwnedForm method is called. In addition to removing the owned form from the list of owned form, this method also sets the owner form to null.

于 2012-11-15T11:42:54.057 回答
1

解决方案:

private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.FormOwnerClosing)
    {
        e.Cancel = true;
        Hide();
    }
}

此解决方案在 Form1_FormClosing 事件中不需要 dlg.Dispose() 和 this.RemoveOwnedForm(dlg)。

于 2012-11-15T13:06:19.347 回答