bestwmb 发表于 2018-3-19 14:50:24

form控件随窗体大小变化

对于设计完窗体后,运行时发现窗体最大化后控件和原来一样,这段祖传代码帮新人解决问题

      /*
         * 设置窗口控件随窗口大小改变而改变
         */
      public new void AutoScale(Form frm)
      {
            frm.Tag = frm.Width.ToString() + "," + frm.Height.ToString();
            frm.SizeChanged += new EventHandler(frm_SizeChanged);
      }
      public void frm_SizeChanged(object sender, EventArgs e)
      {
            string[] tmp = ((Form)sender).Tag.ToString().Split(',');
            float width = (float)((Form)sender).Width / (float)Convert.ToInt32(tmp);
            float height = (float)((Form)sender).Height / (float)Convert.ToInt32(tmp);
            ((Form)sender).Tag = ((Form)sender).Width.ToString() + "," + ((Form)sender).Height;
            string str = ((Form)sender).Tag.ToString();
            // int font_size = Int32.Parse(str.Substring(0, str.IndexOf(','))) / 100;
            //也可使字体随之改变
            float tempWidth = 0F;
            float tempHeight = 0F;
            foreach (Control control in ((Form)sender).Controls)
            {
                if (control is DataGridView)
                  continue;
                if (control is TextBox)
                {
                  tempHeight = height;
                  tempWidth = width;
                }
                if (control is Button)
                {
                  if (this.WindowState == FormWindowState.Maximized)
                        tempHeight -= 0.4F;
                  else
                        tempHeight += 0.2F;
                  control.Scale(new SizeF(tempWidth, tempHeight));
                }
                else
                {
                  try
                  {
                        control.Scale(new SizeF(width, height));
                  }
                  catch
                  {
                  }
                }
            }
      }

bestwmb 发表于 2018-3-19 14:52:33

在form 的load 事件中 调用
AutoScale(this);//设置窗口控件随窗口大小改变而改变

ibcadmin 发表于 2018-3-20 14:13:41

6666666666
页: [1]
查看完整版本: form控件随窗体大小变化