C # Implementation of the MDI form program that prevents a subform from being instantiated multiple times--singleton

Source: Internet
Author: User
When the program went to the CSDN forum at night, I saw a friend in C # who asked "Prevent MDI child forms from being instantiated multiple times", and I wrote this article immediately.

In fact, this problem is the classic 23 design patterns in the single piece mode (Singleton), following the implementation of C #:

First we have 2 Windows Forms, the main form is called Form1, and the subform is called ChildForm. By adding a menu to the main form to instantiate the subform, we write the code in Form1.cs:

private static ChildForm ChildForm; Static variables, saving a unique instance

private void Menuitem2_click (object sender, System.EventArgs e)
{
ChildForm childform = Getchildform (); Get Subform Object
Childform.show (); Show the
}

Private ChildForm Getchildform ()
{
The order can not be wrong, the previous condition to determine whether it is the first time, the latter condition to determine whether the subform is closed
if (ChildForm = null | | childform.isdisposed)
{//The first instantiation, or being shut down, is again instantiated
ChildForm = new ChildForm ();
Childform.mdiparent = this;
}

return childform;
}

----------------------------------------------------------------------------------------------------------
OK, just easy like this! Enjoy it!



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.