WinForm单例窗体用法实例
本文实例讲述了WinForm单例窗体。分享给大家供大家参考,具体如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Windows.Forms; usingSystem.Text; namespaceCommon { ///<summary> ///窗体的单例模式 ///</summary> ///<typeparamname="T"></typeparam> publicclassFormSingle<T>whereT:Form,new() { privatestaticTform; privatestaticIList<T>list{get;set;} publicstaticTGetForm(Tt1) { //检查是否存在窗体 if(!IsExist(t1)) { CreateNewForm(t1); } returnform; } ///<summary>释放对象 ///</summary> ///<paramname="obj"></param> ///<paramname="args"></param> privatestaticvoidDisplay(objectobj,FormClosedEventArgsargs) { form=null; list.Remove(form); } ///<summary>创建新窗体 ///</summary> privatestaticvoidCreateNewForm(Tt1) { form=t1; form.FormClosed+=newFormClosedEventHandler(Display);//订阅窗体的关闭事件,释放对象 } ///<summary> ///是否存在该窗体 ///</summary> ///<paramname="T1"></param> ///<returns></returns> privatestaticboolIsExist(TT1) { if(list==null) { list=newList<T>(); list.Add(T1); returnfalse; } //如果窗体的文本相同则认为是同一个窗体 foreach(vartinlist) { if(t.Text==T1.Text) returntrue; } list.Add(T1); returnfalse; } } }
调用如下:
不带参数的构造函数
Customer.AddCustomercustomer=Common.FormSingle<Customer.AddCustomer>.GetForm(newCustomer.AddCustomer()); customer.MdiParent=this;//Mdi窗体 customer.WindowState=FormWindowState.Maximized;//最大化 customer.Show(); customer.Activate();
带参数的构造函数
Customer.AddCustomercustomer=Common.FormSingle<Customer.AddCustomer>.GetForm(newCustomer.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#程序设计有所帮助。