tags:

views:

88

answers:

1

Is a System.Windows.Forms.Form automatically disposed when the user closes it with the top right X, or Alt+F4 ? The form is shown with form.Show(this), not form.ShowDialog(...);

+13  A: 

With Show, yes it is (at the end of WmClose). With ShowDialog, no it isn't. Fun ;-p

For ShowDialog, see MSDN:

Because a form displayed as a dialog box is not closed, you must call the Dispose method of the form when the form is no longer needed by your application.

To prove it, though:

Form main = new Form();
Form test = new Form();
test.Text = "Close me";
test.Disposed += delegate {
    main.Text = "Second form was disposed";
};
main.Shown += delegate {
    test.Show();
};
Application.Run(main);
Marc Gravell
Wow I did not know this. Can their be memory leaks because of this?
pdiddy
From not disposing forms shown with `ShowDialog`? Well, probably not a *leak*, but it might take longer (GC) to clean up the underlying windows handles.
Marc Gravell
I discovered a leak just because of not Disposing a ShowDialog'ed Form. .Dispose was not called, which meant the controls on the form was never disposed which meant one of the controls did not unregister itself from a SystemEvents handler. So the control never got disposed cause it subscribed to an event(and that event lived for the scope of the application), the control had again a reference to its Form, preventing the whole form and everything on it to never get GC'ed
Anonym