Winform 窗体自适应分辨率

来源:互联网 发布:现代软件学院学费多少 编辑:程序博客网 时间:2024/06/04 19:07

Winform开发时   有时会碰到窗体 碰到不同分辨率而导致  有些控件被盖住的情况  所以还是  让窗体根据电脑分辨率显示大小吧!

第一步:添加类 类中添加实现功能的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PowerSystemByWinForm
{
    public class AutoSizeFormClass
    {
        public struct controlRect
        {
            public int Left;
            public int Top;
            public int Width;
            public int Height;
        }

        private bool _Flag;
        public bool Flag
        {
            get { return _Flag; }
            set { _Flag = value; }
        }

        private int _Number;
        public int Number
        {
            get { return _Number; }
            set { _Number = value; }
        }

        private List<controlRect> oldCtrl;

        public void Initialize(Control mForm)
        {
            oldCtrl = new List<controlRect>();
            controlRect cR;

            cR.Left = mForm.Left;
            cR.Top = mForm.Top;
            cR.Width = mForm.Width;
            cR.Height = mForm.Height;

            oldCtrl.Add(cR);

            foreach (Control c in mForm.Controls)
            {
                controlRect objCtrl;
                objCtrl.Left = c.Left;
                objCtrl.Top = c.Top;
                objCtrl.Width = c.Width;
                objCtrl.Height = c.Height;
                oldCtrl.Add(objCtrl);
            }
            Flag = true;
            Number = mForm.Controls.Count;
        }

        public void ReSize(Control mForm)
        {
            if (!Flag) return;

            float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;
            float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;

            int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
            int ctrlNo = 1;

            try
            {
                if (mForm.Controls.Count != Number) return;
                foreach (Control c in mForm.Controls)
                {
                    ctrLeft0 = oldCtrl[ctrlNo].Left;
                    ctrTop0 = oldCtrl[ctrlNo].Top;
                    ctrWidth0 = oldCtrl[ctrlNo].Width;
                    ctrHeight0 = oldCtrl[ctrlNo].Height;

                    c.Left = (int)(ctrLeft0 * wScale);
                    c.Top = (int)(ctrTop0 * hScale);
                    c.Width = (int)(ctrWidth0 * wScale);
                    c.Height = (int)(ctrHeight0 * hScale);
                    ctrlNo += 1;
                }
            }
            catch
            {
                return;
            }
        }
    }
}


第二步:调用类中的方法  实现窗体效果

private void Form1_Resize(object sender, EventArgs e)
        {
            autoSize.ReSize(pnlMain);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            autoSize.Initialize(pnlMain);
        }


大功告成   不过这只是通过我的程序  可能太复杂的程序   会出不来效果   谨提供思路!!!

原创粉丝点击