Winform 窗體控件最大化自適應(轉)


運行窗體效果如下:

 

 默認點擊最大化效果如下:

 

修改后最大化效果如下:控件自動縮放,

 

步驟實現如下:

1.在窗體中放一個容器(Panel),將容器的Dock屬性設置為Fill。窗體中所有控件都放入這個容器中。

2.創建一個窗體類,該窗體類繼承於原始窗體類,原來的窗體繼承創建的窗體類:如下圖所示

 

 新建一個 NForm 窗體類,繼承默認窗體類 Form ,而原來的 Form1 :Form 窗體類繼承的默認窗體類修改為 Form1 :NForm 自定義新建的窗體類。

新建窗體類代碼如下:

public partial class NForm : Form
{
#region 控件縮放
double formWidth;//窗體原始寬度
double formHeight;//窗體原始高度
double scaleX;//水平縮放比例
double scaleY;//垂直縮放比例
Dictionary<string, string> controlInfo = new Dictionary<string, string>();
//控件中心Left,Top,控件Width,控件Height,控件字體Size
/// <summary>
/// 獲取所有原始數據
/// </summary>
protected void GetAllInitInfo(Control CrlContainer)
{
if (CrlContainer.Parent == this)
{
formWidth = Convert.ToDouble(CrlContainer.Width);
formHeight = Convert.ToDouble(CrlContainer.Height);
}
foreach (Control item in CrlContainer.Controls)
{
if (item.Name.Trim() != "")
controlInfo.Add(item.Name, (item.Left + item.Width / 2) + "," + (item.Top + item.Height / 2) + "," + item.Width + "," + item.Height + "," + item.Font.Size);
if ((item as UserControl) == null && item.Controls.Count > 0)
GetAllInitInfo(item);
}
}
private void ControlsChangeInit(Control CrlContainer)
{
scaleX = (Convert.ToDouble(CrlContainer.Width) / formWidth);
scaleY = (Convert.ToDouble(CrlContainer.Height) / formHeight);
}
private void ControlsChange(Control CrlContainer)
{
double[] pos = new double[5];//pos數組保存當前控件中心Left,Top,控件Width,控件Height,控件字體Size
foreach (Control item in CrlContainer.Controls)
{
if (item.Name.Trim() != "")
{
if ((item as UserControl) == null && item.Controls.Count > 0)
ControlsChange(item);
string[] strs = controlInfo[item.Name].Split(',');
for (int j = 0; j < 5; j++)
{
pos[j] = Convert.ToDouble(strs[j]);
}
double itemWidth = pos[2] * scaleX;
double itemHeight = pos[3] * scaleY;
item.Left = Convert.ToInt32(pos[0] * scaleX - itemWidth / 2);
item.Top = Convert.ToInt32(pos[1] * scaleY - itemHeight / 2);
item.Width = Convert.ToInt32(itemWidth);
item.Height = Convert.ToInt32(itemHeight);
try{
item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));
}
catch{
}
}
}
}

#endregion


protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (controlInfo.Count > 0)
{
ControlsChangeInit(this.Controls[0]);
ControlsChange(this.Controls[0]);
}
}
}
新建的窗體類中主要包括自定義幾個方法,用以實現控件自適應

(1)獲取控件初始信息;GetAllInitInfo()              

(2)獲取窗體縮放比例;ControlsChaneInit()             

(3)窗體改變時修改控件大小。ControlsChange()

最后。在窗體類的構造函數中調用獲取初始數據的方法:

public Form1()
{
InitializeComponent();
GetAllInitInfo(this.Controls[0]);
}
這樣,一個自適應窗體就實現了,再也不用擔心最大化和拖拽后窗體控件位置錯位的尷尬了
————————————————
版權聲明:本文為CSDN博主「凌霜殘雪」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_21419015/article/details/83855275


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM