winform窗體自適應

實現步驟:

1.在窗體中放一個容器(例如:Panel),並且將容器的Dock屬性設置爲Fill。窗體中其他控件都放在這個容器中。

2.創建一個窗體類,該類繼承於原始窗體類,並在新建的這個窗體類中添加如下代碼,以後創建的窗體都繼承於新建的這個窗體類:

#region 控件縮放
double formWidth;//窗體原始寬度
double formHeight;//窗體原始高度
double scaleX;//水平縮放比例
double scaleY;//垂直縮放比例
Dictionary<stringstring> controlInfo = new Dictionary<stringstring>();//控件中心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);
            item.Font = new Font(item.Font.Name, float.Parse((pos[4] * Math.Min(scaleX, scaleY)).ToString()));
        }
    }
}

#endregion 

3.在新建的窗體類中重寫OnSizeChanged事件,並調用ControlsChangeInit和ControlsChange方法,代碼如下:

protected override void OnSizeChanged(EventArgs e)
{
    base.OnSizeChanged(e);
    if (controlInfo.Count > 0)
    {
        ControlsChangeInit(this.Controls[0]);
        ControlsChange(this.Controls[0]);
    }
}

4.在窗體的構造函數中調用GetAllInitInfo方法,代碼如下:

    GetAllInitInfo(this.Controls[0]);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章