Hiding MDI child forms on close using C# [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-23 17:16:04

问题


I'm currently building a multiple-document interface application, but I'm having a problem when the child forms are closed via the x button. When the form is closed, the only way to show it again is to create a new instance of that particular form, meaning all of the data contained within the previous form is lost.

I have attempted to set the form closing event to simply hide the form, but then when the user closes the main parent form, the application does not exit.

Is there a way around this?

Here is the code I am currently using for my child forms' form closing event:

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

With this code, the main form's x button must be clicked twice, once to close the child form and once to close the main form.


回答1:


Forms are intended to be opened and closed by the user. And, indeed, when they are closed, the object instance is subject to being destroyed, causing you to lose all data that is stored in fields or properties associated with that object instance.

Therefore, you should not use form instances as a permanent place to store data. You need to write that data out to disk, save it into a database, or perhaps simply store it in a class instance shared across all of your forms (that, of course, will not be destroyed until you explicitly do so through code, as it has no user interface and can't be "closed" by the user).

However, if you just want to make this work, it's possible to do that as well. You need to change the code in your FormClosing event handler to only prevent the child forms from closing when the e.CloseReason property indicates that they're closing as a result of direct user interaction:

private void ParameterForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        this.Hide();
        e.Cancel = true;
    }
}

The reason that your check doesn't work (e.CloseReason != CloseReason.FormOwnerClosing) is because you have an MDI application. There's a special reason that is used when the MDI parent is closing: CloseReason.MdiFormClosing. You could watch for that also, but it's simpler to do it the way shown above, because you don't want to prevent the windows from being closed when Windows is shutting down either, for example.



来源:https://stackoverflow.com/questions/6020210/hiding-mdi-child-forms-on-close-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!