FormAutoScaling.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Forms;
  7. namespace StandardLibrary
  8. {
  9. class AutoResize
  10. {
  11. private float defaultX = 0;//窗体初始宽度
  12. private float defaultY = 0;//窗体初始高度
  13. Control parentControl = new Control();
  14. public void SetAutoResize(Control cons)
  15. {
  16. this.defaultX = cons.Width;
  17. this.defaultY = cons.Height;
  18. parentControl = cons;
  19. SetControlTag(cons);
  20. cons.Resize += ControlAutoResize;
  21. }
  22. private void SetControlTag(Control cons)
  23. {
  24. foreach (Control con in cons.Controls)
  25. { //设置控件Tag属性的数据位{控件宽度:控件高度:容器左边距离:容器右边距离:文字大小}
  26. con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
  27. if (con.Controls.Count > 0)
  28. SetControlTag(con);
  29. }
  30. }
  31. private void SetControlsAutoScaling(float newx, float newy, Control cons)
  32. {
  33. foreach (Control con in cons.Controls)
  34. {
  35. if (con.Tag == null) continue;//防止动态添加的控件(动态添加的控件没有设置Tag)
  36. string[] mytag = con.Tag.ToString().Split(':');//分割控件的Tag属性值
  37. float controlTags = 0;
  38. controlTags = Convert.ToSingle(mytag[0]) * newx;
  39. con.Width = (int)controlTags;
  40. controlTags = Convert.ToSingle(mytag[1]) * newy;
  41. con.Height = (int)(controlTags);
  42. controlTags = Convert.ToSingle(mytag[2]) * newx;
  43. con.Left = (int)(controlTags);
  44. controlTags = Convert.ToSingle(mytag[3]) * newy;
  45. con.Top = (int)(controlTags);
  46. Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy);
  47. con.Font = new System.Drawing.Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
  48. if (con.Controls.Count > 0) SetControlsAutoScaling(newx, newy, con);
  49. }
  50. }
  51. private void ControlAutoResize(object sender, EventArgs e)
  52. {
  53. float newx = parentControl.Width / defaultX;//获取窗体宽度变化前后大小的比值
  54. float newy = parentControl.Height / defaultY;//获取窗体高度变化前后大小的比值
  55. SetControlsAutoScaling(newx, newy, parentControl);
  56. }
  57. }
  58. }