FormManTool.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. public bool Add<T>(T value) where T : Form
  25. {
  26. _AllForms.Add(value);
  27. return true;
  28. }
  29. /// <summary>
  30. /// 获取唯一窗体对象
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. /// <returns></returns>
  34. public T GetUnique<T>() where T : Form, new()
  35. {
  36. if (UniqueForms.ContainsKey(typeof(T)))
  37. {
  38. // 字典中有该窗体,则读取窗体对象
  39. Form value;
  40. if (UniqueForms.TryGetValue(typeof(T), out value))
  41. {
  42. if (value != null && !value.IsDisposed)
  43. {
  44. // 窗体对象可用(不为空、没释放),反馈窗体对象
  45. return (T)value;
  46. }
  47. else
  48. {
  49. // 窗体对象不可用,从字典中移除窗体对象
  50. Form temp;
  51. UniqueForms.TryRemove(typeof(T), out temp);
  52. }
  53. }
  54. }
  55. // 未能返回正确的窗体,则创建新窗体(使用默认new方法)
  56. T form = new T();
  57. if (AddUnique(form)) return form;
  58. return null;
  59. }
  60. private bool AddUnique<T>(T value) where T : Form, new()
  61. {
  62. if (!UniqueForms.ContainsKey(typeof(T)))
  63. {
  64. if (UniqueForms.TryAdd(typeof(T), value))
  65. {
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71. }
  72. }