AutoSizeControl.cs 3.0 KB

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