WinForm Singleton Form Usage Example
- 2021-10-27 08:41:09
- OfStack
This article illustrates the WinForm singleton form. Share it for your reference, as follows:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
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 a form exists
if (!IsExist(t1))
{
CreateNewForm(t1);
}
return form;
}
/// <summary> Release object
/// </summary>
/// <param name="obj"></param>
/// <param name="args"></param>
private static void Display(object obj, FormClosedEventArgs args)
{
form = null;
list.Remove(form);
}
/// <summary> Create a new form
/// </summary>
private static void CreateNewForm(T t1)
{
form = t1;
form.FormClosed += new FormClosedEventHandler(Display);// Subscribe to the closing event of the form and release the object
}
/// <summary>
/// Whether the form exists
/// </summary>
/// <param name="T1"></param>
/// <returns></returns>
private static bool IsExist(T T1)
{
if (list == null)
{
list=new List<T>();
list.Add(T1);
return false;
}
// If the text of the form is the same, it is considered the same 1 Form
foreach (var t in list)
{
if (t.Text == T1.Text)
return true;
}
list.Add(T1);
return false;
}
}
}
The call is as follows:
Constructor without parameters
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer());
customer.MdiParent = this;//Mdi Form
customer.WindowState = FormWindowState.Maximized;// Maximize
customer.Show();
customer.Activate();
Constructor with parameters
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer(customerid));
customer.MdiParent = this;
customer.WindowState = FormWindowState.Maximized;
customer.Show();
customer.Activate();
More readers interested in C # can check the topic of this site: "WinForm Control Usage Summary", "C # Form Operation Skills Summary", "C # Common Control Usage Tutorial", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "XML File Operation Skills Summary in C #", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"
I hope this article is helpful to everyone's C # programming.