本文实例讲述了WinForm单例窗体。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
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 ; } } } |
调用如下:
不带参数的构造函数
1
2
3
4
5
|
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm( new Customer.AddCustomer()); customer.MdiParent = this ; //Mdi窗体 customer.WindowState = FormWindowState.Maximized; //最大化 customer.Show(); customer.Activate(); |
带参数的构造函数
1
2
3
4
5
|
Customer.AddCustomer customer = Common.FormSingle<Customer.AddCustomer>.GetForm( new Customer.AddCustomer(customerid)); customer.MdiParent = this ; customer.WindowState = FormWindowState.Maximized; customer.Show(); customer.Activate(); |
希望本文所述对大家C#程序设计有所帮助。