SoFunction
Updated on 2025-03-07

WinForm singleton form usage example

This article describes the WinForm singleton form. Share it for your reference, as follows:

using System;
using ;
using ;
using ;
namespace Common
{
  /// <summary>
  /// Singleton mode of form  /// </summary>
  /// <typeparam name="T"></typeparam>
  public class FormSingle<T> where T : Form, new()
  {
    private static T form;
    private static IList<T> list { get; set; }
    public static T GetForm(T t1)
    {
      //Check whether the form exists      if (!IsExist(t1))
      {
        CreateNewForm(t1);
      }
      return form;
    }
    /// <summary>Release the object    /// &lt;/summary&gt;
    /// &lt;param name="obj"&gt;&lt;/param&gt;
    /// &lt;param name="args"&gt;&lt;/param&gt;
    private static void Display(object obj, FormClosedEventArgs args)
    {
      form = null;
      (form);
    }
    /// <summary>Create a new form    /// &lt;/summary&gt;
    private static void CreateNewForm(T t1)
    {
      form = t1;
       += new FormClosedEventHandler(Display);//Subscribe to the form's closing event and release the object    }
    /// &lt;summary&gt;
    /// Whether this form exists    /// &lt;/summary&gt;
    /// &lt;param name="T1"&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    private static bool IsExist(T T1)
    {
      if (list == null)
      {
        list=new List&lt;T&gt;();
        (T1);
        return false;
      }
      //If the text of the form is the same, it is considered to be the same form      foreach (var t in list)
      {
        if ( == )
          return true;
      }
      (T1);
      return false;
    }
  }
}

The call is as follows:

Constructor without parameters

 customer = &lt;&gt;.GetForm(new ());
 = this;//Mdi Form = ;//maximize();
();

Constructor with parameters

 customer = <>.GetForm(new (customerid));
 = this;
 = ;
();
();

For more information about C# related content, please check out the topic of this site:Summary of WinForm control usage》、《Summary of C# form operation skills》、《Tutorial on the usage of common C# controls》、《Summary of thread usage techniques for C# programming》、《Summary of C# operation skills》、《Summary of XML file operation skills in C#》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.