C#/WinForms: ShowDialog and subsequent Show on Form

时光怂恿深爱的人放手 提交于 2019-12-06 09:22:08

Are you sure you don't have this backward? I created a simple blank form to use as a modal dialog, and then tested it with a simple form that just has a button that shows the dialog.

public partial class Form1 : Form
{
    private MyDialog theDialog;
    public Form1()
    {
        InitializeComponent();
        theDialog = new MyDialog();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        theDialog.ShowDialog();
    }
}

I can show the dialog repeatedly with no trouble.

Now, if I call theDialog.Show(), close it, and then try to show it again, I get a ObjectDisposedException.

So, the documentation is correct: ShowDialog does not call Form.Close, whereas Show apparently does.

EDIT:

The documentation for Form.Close tells you what you have to do if you want to prevent the form from being destroyed:

You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler.

With that information and a few minutes' thought, it's trivial to have a form that you can show as modal or non-modal:

public partial class Form1 : Form
{
    private MyDialog theDialog;
    public Form1()
    {
        InitializeComponent();
        theDialog = new MyDialog();
        theDialog.FormClosing += new FormClosingEventHandler(theDialog_FormClosing);
    }

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

    private void button1_Click(object sender, EventArgs e)
    {
        if (theDialog.Visible)
        {
            theDialog.BringToFront();
        }
        else
        {
            theDialog.ShowDialog();
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (theDialog.Visible)
        {
            theDialog.BringToFront();
        }
        else
        {
            theDialog.Show();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!