Form.DialogResult Does Not Call Close Method Automatically

2011-07-05


When we use Form.DialogResult in our Windows Form project, we should know it just return a DialogResult, it does NOT call a Close method to close the form automatically. Even you click the Close icon in the top-right corner of the form to close the form.

When a form is displayed as a modal dialog box, setting DialogResult enumeration value as the result for the form, it will hide the modal dialog box, and returns control to the calling form. But the form is just hidden, it is still there. The Close method is not called automatically. If you click the Close icon in the top-right corner of the form, it just causes the form to be hidden too. If you want to close the form, you have to load Dispose method in your code.

Here is a sample:

private void CfgToolStripMenuItem_Click(object sender, EventArgs e)
{
    ConfigForm cfgForm = new ConfigForm();
    //cfgForm.Show(this);

    if (cfgForm.ShowDialog() == DialogResult.OK)
    {
        if (this.imgBrs != null)
        {
            this.imgBrs.ReLoadCfg();
            this.imgBrs.InitImageBrowser();
        }
    }

    cfgForm.Dispose();

}

_Note (from MSDN):

If a Form is displayed as a modeless window, the value returned by the DialogResult property might not return a value assigned to the form because the form's resources are automatically released when the form is closed._