C#中Winform如何实现控件自适应父容器大小

发布时间:2021-03-24 11:46:37 作者:小新
来源:亿速云 阅读:430

小编给大家分享一下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如何实现控件自适应父容器大小”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. WinForm中如何使用listBox控件
  2. winform 控件置顶

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

winform

上一篇:MyBatisPlus逻辑删除与唯一索引冲突的示例分析

下一篇:JDBC连接Mysql长时间无动作连接失效怎么办

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》