FormManTool.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.7.31 - 2017.7.31
  5. // desc: 窗体管理器
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Windows.Forms;
  14. namespace Y.Utils.WindowsUtils.FormUtils
  15. {
  16. /// <summary>
  17. /// 窗体管理器
  18. /// </summary>
  19. public class FormManTool
  20. {
  21. protected ConcurrentDictionary<Type, Form> UniqueForms = new ConcurrentDictionary<Type, Form>();
  22. public List<Form> AllForms { get { return _AllForms; } }
  23. private List<Form> _AllForms = new List<Form>();
  24. /// <summary>
  25. /// 获取窗体对象
  26. /// </summary>
  27. /// <typeparam name="T"></typeparam>
  28. /// <returns></returns>
  29. public T Get<T>() where T : Form, new()
  30. {
  31. if (UniqueForms.ContainsKey(typeof(T)))
  32. {
  33. // 字典中有该窗体,则读取窗体对象
  34. Form value;
  35. if (UniqueForms.TryGetValue(typeof(T), out value))
  36. {
  37. if (value != null && !value.IsDisposed)
  38. {
  39. // 窗体对象可用(不为空、没释放),反馈窗体对象
  40. return (T)value;
  41. }
  42. else
  43. {
  44. // 窗体对象不可用,从字典中移除窗体对象
  45. Form temp;
  46. UniqueForms.TryRemove(typeof(T), out temp);
  47. }
  48. }
  49. }
  50. // 未能返回正确的窗体,则创建新窗体(使用默认new方法)
  51. T form = new T();
  52. if (UniqueForms.TryAdd(typeof(T), form))
  53. {
  54. // 添加到字典成功后,返回当前窗体对象
  55. _AllForms.Add(form);
  56. return form;
  57. }
  58. return null;
  59. }
  60. }
  61. }