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 控件自適應父容器大小內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!