1. Create a New winformProgram, Drag a button to the default form1, and then create a new form2.
2. Change form2's default constructor to private, and then add a static variable and instantiated function,CodeAs follows:
Private Static bool instanceflag = false; private form2 () {instanceflag = true; initializecomponet ();} public static form2 createinstance () {return instanceflag? Null: New form2 ();}
3. Write the following code in the form1 button_click event:
Private void button#click (Object sender, eventargs e) {form2 fm = form2.createinstance (); If (FM! = NULL) fm. Show ();}
In this way, no matter how many times you click button1, there will be only one form2 instance
This method can also be improved. For example, form2 can only instantiate up to three instances. You only need to modify the code in form2 as follows:
Private Static int instanceflag = 0; private form2 () {instanceflag ++; initializecomponet ();} public static form2 createinstance () {return instanceflag> = 3? Null: New form2 ();}