问题
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