The same window in winform can only be displayed once.

Source: Internet
Author: User

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 ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.