FormManTool.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 Azylee.Core.DataUtils.CollectionUtils;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.Windows.Forms;
  14. namespace Azylee.WinformMan.ManagerUtils
  15. {
  16. /// <summary>
  17. /// 窗体管理器
  18. /// </summary>
  19. public class FormManTool
  20. {
  21. public Color? BackColor = null;
  22. protected ConcurrentDictionary<Type, Form> UniqueForms = new ConcurrentDictionary<Type, Form>();
  23. public List<Form> AllForms { get { return _AllForms; } }
  24. private List<Form> _AllForms = new List<Form>();
  25. public bool Add<T>(T form) where T : Form
  26. {
  27. if (BackColor != null) form.BackColor = (Color)BackColor;
  28. _AllForms.Add(form);
  29. return true;
  30. }
  31. /// <summary>
  32. /// 获取唯一窗体对象
  33. /// </summary>
  34. /// <typeparam name="T"></typeparam>
  35. /// <returns></returns>
  36. public T GetUnique<T>() where T : Form, new()
  37. {
  38. if (UniqueForms.ContainsKey(typeof(T)))
  39. {
  40. // 字典中有该窗体,则读取窗体对象
  41. Form value;
  42. if (UniqueForms.TryGetValue(typeof(T), out value))
  43. {
  44. if (value != null && !value.IsDisposed)
  45. {
  46. // 窗体对象可用(不为空、没释放),反馈窗体对象
  47. return (T)value;
  48. }
  49. else
  50. {
  51. // 窗体对象不可用,从字典中移除窗体对象
  52. Form temp;
  53. UniqueForms.TryRemove(typeof(T), out temp);
  54. }
  55. }
  56. }
  57. // 未能返回正确的窗体,则创建新窗体(使用默认new方法)
  58. T form = new T();
  59. if (BackColor != null) form.BackColor = (Color)BackColor;
  60. if (AddUnique(form)) return form;
  61. return null;
  62. }
  63. private bool AddUnique<T>(T value) where T : Form, new()
  64. {
  65. if (!UniqueForms.ContainsKey(typeof(T)))
  66. {
  67. if (UniqueForms.TryAdd(typeof(T), value))
  68. {
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. /// <summary>
  75. /// 设置所有窗体的背景色
  76. /// </summary>
  77. /// <param name="c"></param>
  78. public void SetAllBackColor(Color c)
  79. {
  80. if (ListTool.HasElements(AllForms))
  81. {
  82. foreach (var form in AllForms)
  83. {
  84. if (form != null && !form.IsDisposed)
  85. form.BackColor = c;
  86. }
  87. }
  88. }
  89. }
  90. }