For example, in a Windows application, open a form with the following code:
The code is as follows |
Copy Code |
private void Button1_Click (object sender, EventArgs e) { (New About ()). Show (); } |
The result is that each click of the button opens a form, which may end up as follows:
This obviously I'm not what we want, normal should be when you click on the button to determine whether the form has been opened, have opened the display activation form, did not create and open the form, to modify the code slightly:
code is as follows |
copy code |
private void Button1_Click (object sender, EventArgs e) { if (frmabout = = NULL | | frmabout.isdisposed) &N bsp; { frmabout = new About (); Frmabout.show (this); } Else { Frmabout.windowstate = Formwindowstate.normal; frmabout.activate (); } } Private about frmabout = null; |
This can meet the top requirements, but if there are multiple places to open the form, the same code will have to copy many times, in this scenario, we can use the single example mode to solve:
The code is as follows |
Copy Code |
About.cs: Using System; Using System.Text; Using System.Windows.Forms; Namespace WindowsFormsApplication1 { public partial class About:form { <summary> Constructors cannot be called externally </summary> Private About () { InitializeComponent (); } <summary> Single case mode </summary> <returns></returns> public static about getinstance () { if (_frmabout = null | | _frmabout.isdisposed) { _frmabout = new About (); } return _frmabout; } private static about _frmabout = NULL; } } |
Call Method:
code is as follows |
copy code |
private void Button1_Click (object sender, EventArgs e) { about frmabout = About.getinstance (); & nbsp; frmabout.show (); frmabout.windowstate = formwindowstate.normal; frmabout.activate (); } |