Search code examples
c#winformsdisposeformclosing

How do I prevent a form object from disposing on close?


I am using an MDIParent Form. When I close its child, the object of the child disposes. Is there a way to set child visibility to false instead of disposing?


Solution

  • By default, when you close a form, it will be disposed. You have to override the Closing event to prevent it, for example:

    // Use this event handler for the FormClosing event.
    private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
    {
      this.Hide();
      e.Cancel = true; // this cancels the close event.
    }
    

    Remember to add the method, e.g. in the form ctor:

    public MyForm()
    {
        InitializeComponent();
    
        this.FormClosing += MyForm_FormClosing;
    }