本文實例講述了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();
更多關于C#相關內容感興趣的讀者可查看本站專題:《WinForm控件用法總結》、《C#窗體操作技巧匯總》、《C#常見控件用法教程》、《C#程序設計之線程使用技巧總結》、《C#操作Excel技巧總結》、《C#中XML文件操作技巧匯總》、《C#數據結構與算法教程》、《C#數組操作技巧總結》及《C#面向對象程序設計入門教程》
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答