C implements the method of closing child windows without releasing child window objects

  • 2021-11-29 08:12:46
  • OfStack

In the debugging process of online scanning camera, it is necessary to open a debugging interface to configure the position. After debugging, a common way is to save the debugging parameters and load them at the next startup. Another simple way is to run the program directly with this parameter. Therefore, in the latter case, the function you need to implement is that even if you close the debug window, its window object will not be released. Destroys objects in its debug window unless its main window is closed.

1 instantiate child windows in the main window

Instantiate child windows in the main window, not child window objects in buttons.

Form2 f2 = new Form2();

2 Display the main window through buttons

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


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

3 Method of closing child window without releasing child window object

After inquiry and demonstration, the method of modifying Dispose in sub-window is feasible. Change as follows:


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

4 Destroy child window objects when parent window closes

Since it is necessary to destroy the child window object when the parent window is closed, a destruction function calling the child window f2 is added to the closing action FormClosed of the parent window.


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

The closing functions added in the child window class are as follows:


 public void Close()
    {

      this.Dispose();

    }


Related articles: