简单是实现winform控件随窗体的大小改变而改变(坐标+大小)

       

着急写的不用Anchor和Dock实现的一个关于窗体控件随窗体大小改变的代码.  命名有点不规范..  哪里写的不好.还请各位大神批评哈..嘿嘿

/// <summary>
        /// 帮助类.用于保存第一次加载时的控件的坐标和宽度
        /// </summary>
        public class hp
        {
            public Size s { set; get; }
            public Point p { set; get; }
        }
        /// <summary>
        /// 字典.用于保存每个控件的名字.和每个控件的帮助类
        /// </summary>
        Dictionary<string, hp> dictMain = new Dictionary<string, hp>();

        /// <summary>
        /// 设置宽度初始化事件
        /// </summary>
        /// <param name="fm">窗体 </param>
        public void SetSize(Form fm)
        {
           //实例化帮助类.保存当前窗体的宽度.
            hp hf = new hp();
            hf.s = fm.Size;
            dictMain.Add(fm.Name, hf);

            //遍历每个控件的宽度
            foreach (Control c in this.Controls)
            {

                hp h = new hp();
                h.p = c.Location;//坐标
                h.s = c.Size;//宽度
                dictMain.Add(c.Name, h);//保存
            }
            //注册事件
            fm.SizeChanged += new EventHandler(fm_SizeChanged);
        }

        //窗体size改变时
        void fm_SizeChanged(object sender, EventArgs e)
        {
            //获取窗体.以及改变后的窗体的Size
            Form fm = sender as Form;
            Size s = fm.Size;

            if (!dictMain.Keys.Contains(fm.Name))
            {
                return;
            }
            //获取第一次的size
            Size size = dictMain[fm.Name].s;

            //获取控件改变比例的精度
            Double dw = (double)s.Width / size.Width;
            double dh = (double)s.Height / size.Height;

            //遍历每个控件
            foreach (Control c in this.Controls)
            {
                //如果含有当前控件
                if (dictMain.Keys.Contains(c.Name))
                {
                    //获取第一次加载时控件的坐标以及大小
                    hp h = dictMain[c.Name];
                    Point np = h.p;
                    Size nz = h.s;

                    //重新得到乘以精度后的X,Y,宽,高
                    np.X = Convert.ToInt32(np.X * dw);
                    np.Y = Convert.ToInt32(np.Y * dh);
                    nz.Width = Convert.ToInt32(nz.Width * dw);
                    nz.Height = Convert.ToInt32(nz.Height * dh);

                    //重新赋值
                    c.Location = np;
                    c.Size = nz;

                }
            }
        }


<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
展开阅读全文

没有更多推荐了,返回首页