1. 程式人生 > >C#根據Form大小控制元件自動更改大小(自適應)

C#根據Form大小控制元件自動更改大小(自適應)

長話短說,直接上程式碼  C#的

1.軟體Form中加入ResizeBegin 或ResizeEnd 事件,或下面兩行加入Form_Load裡面

this.ResizeBegin += new System.EventHandler(this.Form1_ResizeBegin); this.ResizeEnd += new System.EventHandler(this.Form1_ResizeEnd);

2.定義變數,

        /// <summary>         /// 比例,寬度         /// </summary>       private  int iForm_default_Width;         /// <summary>         /// 比例,長度         /// </summary>       private  int iForm_default_Height;

3.寫程式碼,此例子中的Form名為 Form1          private void Form1_ResizeBegin(object sender, EventArgs e)         {             //獲得預設軟體大小             iForm_default_Width = this.Size.Width;             iForm_default_Height = this.Size.Height;         }

        private void Form1_ResizeEnd(object sender, EventArgs e)         {             #region 控制控制元件自適應UI大小             float fRatio_Width = ((float)iForm_default_Width) / this.Size.Width;             float fRatio_Height = ((float)iForm_default_Height) / this.Size.Height;             foreach (Control OneCon in this.Controls)   //根據原大小等比例放大             {  //此處為重點,查詢控制元件內所有寫控制元件,並等比例修改位置及大小 //寫於2018-9-19 11:17:01                 OneCon.Left = Convert.ToInt32(OneCon.Left / fRatio_Width);                 OneCon.Top = Convert.ToInt32(OneCon.Top / fRatio_Height);                 OneCon.Width = Convert.ToInt32(OneCon.Width / fRatio_Width);                 OneCon.Height = Convert.ToInt32(OneCon.Height / fRatio_Height);             }             #endregion         }