FormManTool.cs 3.1 KB

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