AutoSizeControl.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System.Collections.Generic;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace UAS_MES_NEW.PublicMethod
  5. {
  6. class AutoSizeControl
  7. {
  8. /// <summary>
  9. /// 记录所有控件
  10. /// </summary>
  11. List<Control> ctl = new List<Control>();
  12. /// <summary>
  13. /// 记录控件的初始化位置
  14. /// </summary>
  15. Dictionary<string, Point> CtlPoint = new Dictionary<string, Point>();
  16. /// <summary>
  17. /// 记录控件的初始化大小
  18. /// </summary>
  19. Dictionary<string, Size> CtlSize = new Dictionary<string, Size>();
  20. /// <summary>
  21. /// 初始化的窗体宽度
  22. /// </summary>
  23. int InitFormWidth = 0;
  24. /// <summary>
  25. /// 初始化的窗体高度
  26. /// </summary>
  27. int InitFormHeight = 0;
  28. /// <summary>
  29. /// 窗体调整时的宽度
  30. /// </summary>
  31. int AutoSizeFormWidth = 0;
  32. /// <summary>
  33. /// 窗体调整时的高度
  34. /// </summary>
  35. int AutoSizeFormHeight = 0;
  36. /// <summary>
  37. /// 自适应宽度比例
  38. /// </summary>
  39. float AutoSizeWidthRate;
  40. /// <summary>
  41. ///
  42. /// </summary>
  43. float AutoSizeHeigthRate;
  44. public void InitControl(Control control)
  45. {
  46. InitFormWidth = control.Width;
  47. InitFormHeight = control.Height;
  48. foreach (Control item in control.Controls)
  49. {
  50. ctl.Add(item);
  51. CtlPoint.Add(item.Name, item.Location);
  52. CtlSize.Add(item.Name, item.Size);
  53. if (item.Controls.Count > 0)
  54. {
  55. AddControl(item);
  56. }
  57. }
  58. }
  59. public void AddControl(Control control)
  60. {
  61. foreach (Control item in control.Controls)
  62. {
  63. ctl.Add(item);
  64. if (!CtlPoint.ContainsKey(item.Name))
  65. CtlPoint.Add(item.Name, item.Location);
  66. if (!CtlSize.ContainsKey(item.Name))
  67. CtlSize.Add(item.Name, item.Size);
  68. if (item.Controls.Count > 0)
  69. {
  70. AddControl(item);
  71. }
  72. }
  73. }
  74. public void AutoSize(Control control)
  75. {
  76. AutoSizeFormHeight = control.Height;
  77. AutoSizeFormWidth = control.Width;
  78. AutoSizeWidthRate = (float)(AutoSizeFormWidth * 1.0 / InitFormWidth);
  79. AutoSizeHeigthRate = (float)(AutoSizeFormHeight * 1.0 / InitFormHeight);
  80. for (int i = 0; i < ctl.Count; i++)
  81. {
  82. ctl[i].Location = new Point((int)(CtlPoint[ctl[i].Name].X * AutoSizeWidthRate), (int)(CtlPoint[ctl[i].Name].Y * AutoSizeHeigthRate));
  83. ctl[i].Size = new Size((int)(CtlSize[ctl[i].Name].Width * AutoSizeWidthRate), (int)(CtlSize[ctl[i].Name].Height * AutoSizeHeigthRate));
  84. }
  85. }
  86. }
  87. }