AutoSizeControl.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Windows.Forms;
  5. namespace TestProject
  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. int InitFormWidth = 0;
  21. /// <summary>
  22. /// 初始化的窗体高度
  23. /// </summary>
  24. int InitFormHeight = 0;
  25. /// <summary>
  26. /// 窗体调整时的宽度
  27. /// </summary>
  28. int AutoSizeFormWidth = 0;
  29. /// <summary>
  30. /// 窗体调整时的高度
  31. /// </summary>
  32. int AutoSizeFormHeight = 0;
  33. /// <summary>
  34. /// 自适应宽度比例
  35. /// </summary>
  36. float AutoSizeWidthRate;
  37. /// <summary>
  38. ///
  39. /// </summary>
  40. float AutoSizeHeigthRate;
  41. public void InitControl(Control control)
  42. {
  43. InitFormWidth = control.Width;
  44. InitFormHeight = control.Height;
  45. foreach (Control item in control.Controls)
  46. {
  47. ctl.Add(item);
  48. CtlPoint.Add(item.Name, item.Location);
  49. if (item.Controls.Count > 0)
  50. {
  51. AddControl(item);
  52. }
  53. }
  54. }
  55. public void AddControl(Control control)
  56. {
  57. foreach (Control item in control.Controls)
  58. {
  59. ctl.Add(item);
  60. CtlPoint.Add(item.Name, item.Location);
  61. if (item.Controls.Count > 0)
  62. {
  63. AddControl(item);
  64. }
  65. }
  66. }
  67. public void AutoSize(Control control)
  68. {
  69. AutoSizeFormHeight = control.Height;
  70. AutoSizeFormWidth = control.Width;
  71. AutoSizeWidthRate = (float)(AutoSizeFormWidth * 1.0 / InitFormWidth);
  72. AutoSizeHeigthRate = (float)(AutoSizeFormHeight * 1.0 / InitFormHeight);
  73. for (int i = 0; i < ctl.Count; i++)
  74. {
  75. ctl[i].Location = new Point((int)(CtlPoint[ctl[i].Name].X * AutoSizeWidthRate), (int)(CtlPoint[ctl[i].Name].Y * AutoSizeHeigthRate));
  76. }
  77. }
  78. }
  79. }