C# Winform 实现控件自适应父容器大小的示例

在日常开发中经常遇到控件不能随着父容器大小的改变而且自动改变控件的所在位置和大小。以下是实现的代码:

/// <summary>
/// 根据父容器实现控件自适应大小位置
/// </summary>
/// <param name="control">所需自适应大小位置的控件</param>
private void ChangeLocationSizeByParent (Control control)
{
  //记录父容器大小,来判断改变控件大小位置是因为父容器的改变还是通过设置控件大小位置去改变
  Size parentOldSize = control.Parent.Size;

  PointF locationPF = new PointF();
  locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
  locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
  
  PointF sizePF = new PointF();
  sizePF.X = (float)control.Width / (float)control.Parent.Width;
  sizePF.Y = (float)control.Height / (float)control.Parent.Height;

  control.LocationChanged += delegate (Object o, EventArgs e) {

    if (control.Parent != null&&parentOldSize.Equals(control.Parent.Size))
    {
      locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
      locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
      
    }
  };
  control.SizeChanged += delegate (Object o, EventArgs e) {

    if (control.Parent != null && parentOldSize.Equals(control.Parent.Size))
    {
      sizePF.X = (float)control.Width / (float)control.Parent.Width;
      sizePF.Y = (float)control.Height / (float)control.Parent.Height;
      
    }
  };
  control.ParentChanged += delegate (Object o, EventArgs e) {
    if (control.Parent == null)
    {
      return;
    }
    locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
    locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
    sizePF.X = (float)control.Width / (float)control.Parent.Width;
    sizePF.Y = (float)control.Height / (float)control.Parent.Height;
  };
  control.Parent.SizeChanged += delegate (Object po, EventArgs pe) {

    Control pControl = (Control)po;
    int x = (int)(pControl.Width * locationPF.X);
    int y = (int)(pControl.Height * locationPF.Y);
    control.Location = new Point(x, y);
    int width = (int)(pControl.Width * sizePF.X);
    int hetght = (int)(pControl.Height * sizePF.Y);
    control.Size = new Size(width, hetght);
    control.Refresh();
    parentOldSize = pControl.Size;
  };
}

关于C# Winform 实现控件自适应父容器大小的示例代码的文章就介绍至此,更多相关C# Winform 控件自适应父容器大小内容请搜索编程宝库以前的文章,希望大家多多支持编程宝库

C#实现多态主要有3种方法,虚方法,抽象类,接口: 1 虚方法在父类的方法前面加关键字virtual, 子类重写该方法时在方法名前面加上override关键字,例如下面的Person类的SayHello方 ...