一、實現(xiàn)效果
1.1、未啟用控件縮放的實現(xiàn)效果
即:未啟用控件縮放效果代碼時,控件內(nèi)容都是固定在窗體界面的指定位置,不會跟隨窗體的拉伸,放大而進行適配,如下圖所示:
1.2、啟用控件縮放的實現(xiàn)效果
即:啟用控件縮放效果代碼時,控件內(nèi)容會跟隨窗體的拉伸,放大而進行適配,如下圖所示:
二、實現(xiàn)控件隨窗體縮放適配
2.1、控件隨窗體縮放適配思路
實現(xiàn)思路是:
①在窗體初始化時先獲取窗體的寬度和高度,然后;
②遍歷窗體控件進行初始化設(shè)置縮放位置;
③在窗體變化時獲取當前窗體的寬度和高度,然后遍歷窗體控件進行設(shè)置。
2.2、控件隨窗體適配的核心代碼
#region 控件大小隨窗體大小等比例縮放
private readonly float x; //定義當前窗體的寬度
private readonly float y; //定義當前窗體的高度
private void setTag(Control cons)
{
foreach (Control con in cons.Controls)
{
con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
if (con.Controls.Count > 0) setTag(con);
}
}
private void setControls(float newx, float newy, Control cons)
{
//遍歷窗體中的控件,重新設(shè)置控件的值
foreach (Control con in cons.Controls)
//獲取控件的Tag屬性值,并分割后存儲字符串數(shù)組
if (con.Tag != null)
{
var mytag = con.Tag.ToString().Split(';');
//根據(jù)窗體縮放的比例確定控件的值
con.Width = Convert.ToInt32(Convert.ToSingle(mytag[0]) * newx); //寬度
con.Height = Convert.ToInt32(Convert.ToSingle(mytag[1]) * newy); //高度
con.Left = Convert.ToInt32(Convert.ToSingle(mytag[2]) * newx); //左邊距
con.Top = Convert.ToInt32(Convert.ToSingle(mytag[3]) * newy); //頂邊距
var currentSize = Convert.ToSingle(mytag[4]) * newy; //字體大小
if (currentSize > 0) con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
con.Focus();
if (con.Controls.Count > 0) setControls(newx, newy, con);
}
}
/// <summary>
/// 重置窗體布局
/// </summary>
private void ReWinformLayout()
{
var newx = Width / x;
var newy = Height / y;
setControls(newx, newy, this);
}
#endregion
三、使用方法
3.1、在窗體構(gòu)造函數(shù)內(nèi)初始化適配
//注意:UIComponetForm是自己需進行適配的窗體名稱
public UIComponetForm()
{
InitializeComponent();
#region 初始化控件縮放
x = Width;
y = Height;
setTag(this);
#endregion
}
3.2、重置縮放布局
文章來源:http://www.zghlxwxcb.cn/news/detail-416157.html
private void UIComponetForm_Resize(object sender, EventArgs e)
{
//重置窗口布局
ReWinformLayout();
}
至此通過使用C#代碼實現(xiàn)窗體控件適配(自適應(yīng)窗體)布局下過完成,運行項目即可查看效果。文章來源地址http://www.zghlxwxcb.cn/news/detail-416157.html
到了這里,關(guān)于Winform中實現(xiàn)窗體控件適配(自適應(yīng)窗體)布局_通過C#代碼方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!