本文實例講述了WinForm單例窗體。分享給大家供大家參考,具體如下:
using System;using System.Collections.Generic;using System.Windows.Forms;using System.Text;namespace Common{  /// <summary>  /// 窗體的單例模式  /// </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)    {      //檢查是否存在窗體      if (!IsExist(t1))      {        CreateNewForm(t1);      }      return form;    }    /// <summary>釋放對象    /// </summary>    /// <param name="obj"></param>    /// <param name="args"></param>    private static void Display(object obj, FormClosedEventArgs args)    {      form = null;      list.Remove(form);    }    /// <summary>創建新窗體    /// </summary>    private static void CreateNewForm(T t1)    {      form = t1;      form.FormClosed += new FormClosedEventHandler(Display);//訂閱窗體的關閉事件,釋放對象    }    /// <summary>    /// 是否存在該窗體    /// </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;      }      //如果窗體的文本相同則認為是同一個窗體      foreach (var t in list)      {        if (t.Text == T1.Text)          return true;      }      list.Add(T1);      return false;    }  }}調用如下:
不帶參數的構造函數
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer());customer.MdiParent = this;//Mdi窗體customer.WindowState = FormWindowState.Maximized;//最大化customer.Show();customer.Activate();
帶參數的構造函數
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm(new Customer.AddCustomer(customerid));customer.MdiParent = this;customer.WindowState = FormWindowState.Maximized;customer.Show();customer.Activate();
新聞熱點
疑難解答