SoFunction
Updated on 2025-04-06

C# implements a method to close a child window without releasing a child window object

During the debugging process of online scanning cameras, a debugging interface needs to be opened to configure the location. After debugging is finished, a common way is to save the debug parameters and load them on the next startup. Another simple way is to run the program directly with that parameter. Therefore, in the latter case, the function that needs to be implemented is: even if the debug window is closed, its window object will not be released. The object of its debug window is destroyed unless its main window is closed.

1 Instantiate the child window in the main window

Instantiate the child window in the main window, instead of instantiating the child window object in the button.

Form2 f2 = new Form2();

2 Display the main window through the button

What needs to be implemented in the button is the display of the window

private void Config_Click(object sender, EventArgs e)
    {
      ();
    }

3. Method to close the child window without releasing the child window object

After query and empirical investigation, it is feasible to modify the Dispose in the sub-window. Changes are as follows:

 protected override void Dispose(bool disposing)
    {
      Hide();
      //if (disposing && (components != null))
      //{
      //  ();
      //}
      //(disposing);
    }

4 Destroy child window object when parent window closes

Since it is necessary to destroy the child window object when closing the parent window, add the destruction function that calls child window f2 in the closing action FormClosed of the parent window.

 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
      ();
    }  

The closing function added in the subwindow class is as follows:

 public void Close()
    {

      ();

    }

The above method of C# to close a child window without releasing a child window object is all the content I share with you. I hope you can give you a reference and I hope you can support me more.