C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼
更新時間:2021年03月24日 10:39:44 作者:lcsyhh
這篇文章主要介紹了C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
在日常開發(fā)中經(jīng)常遇到控件不能隨著父容器大小的改變而且自動改變控件的所在位置和大小。以下是實現(xiàn)的代碼
/// <summary>
/// 根據(jù)父容器實現(xiàn)控件自適應(yīng)大小位置
/// </summary>
/// <param name="control">所需自適應(yīng)大小位置的控件</param>
private void ChangeLocationSizeByParent (Control control)
{
//記錄父容器大小,來判斷改變控件大小位置是因為父容器的改變還是通過設(shè)置控件大小位置去改變
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;
};
}
到此這篇關(guān)于C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼的文章就介紹到這了,更多相關(guān)C# Winform 控件自適應(yīng)父容器大小內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件
這篇文章主要介紹了C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件,本文使用C#代碼實現(xiàn)DLL文件的切換,需要的朋友可以參考下2014-09-09
VS2019屬性管理器沒有Microsoft.Cpp.x64.user的解決辦法
這篇文章主要介紹了VS2019屬性管理器沒有Microsoft.Cpp.x64.user的解決辦法,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
C# DataSet的內(nèi)容寫成XML時如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢問一個問題,那就是在將DataSet的內(nèi)容寫成XML時,如何格式化字段數(shù)據(jù)。最常見的需求,就是希望日期時間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02

