Release of form after switching in C # WinForm and prevention of repeated generation


Question 1: how to close the window after switching and release the information?

In C # WinForm, two forms, form1 and form2, are executed when they switch to each other

Form2 form2 = new Form2();



At this point, you will find that when form2 appears, form1 is hidden, but when you close form2, its process is not closed. That is to say, resources are not released!

I looked up a lot of information on the Internet, but many of them have not been solved

As long as the main window is closed, all resources will be released,

However, when the slave window is closed (form2), the resource is not released. At this time, the resource can be released in form2_ Add the following code to the formclosed (object sender, formclosed event args E) event:

Application.Exit (); / / notify all messages to terminate, close all forms after termination, and release resources

Question 2: formThe solution of not repeating new form

Method 1: solution: set the established form to static state, make it unique in memory, and call the object in memory every time you click.

Public static form2 F2 = null; // / set to a global variable for the rest of the forms
if (F2 == null || F2.IsDisposed) 
F2 = new Form2(); 
F2. Show(); // open if not previously opened.
F2. Activate(); // if it has been opened before, focus will be given and top will be set.


Method 2Using ShowDialog

Window opening is a very common method in C #. You can query from one interface to another, but how can you control that the open window cannot be opened repeatedly? You can use ShowDialog method instead of show method

Newdialog d = new Newdialog();


For more C# knowledge, please scan the two-dimensional code below the official account.



If you need to add wechat communication group, please add Xiaobian wechat z438679770, and remember the remarksAdditive groupXiaobian will invite you to join the group for the first time!


Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]