C#窗体控件,文字随电脑分辨率自动调整大小

一、在类中添加方法,代码如下:
#region 窗体控件、字体随分辨率调整,自动调整大小
        public static 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)
 
                    类.Main.SetTag(con);
            }
        }
        public static void SetControls(float newx, float newy, Control cons)
        {
 
            foreach (Control con in cons.Controls)
            {
                try
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
 
                    float a = Convert.ToSingle(mytag[0]) * newx;
 
                    con.Width = (int)a;
 
                    a = Convert.ToSingle(mytag[1]) * newy;
 
                    con.Height = (int)(a);
 
                    a = Convert.ToSingle(mytag[2]) * newx;
 
                    con.Left = (int)(a);
 
                    a = Convert.ToSingle(mytag[3]) * newy;
 
                    con.Top = (int)(a);
 
                    Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy);
 
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
 
                    if (con.Controls.Count > 0)
                    {
                        类.Main.SetControls(newx, newy, con);
                    }
                }
                catch
                {
 
                }
            }
        }
        #endregion

  注:类中需要引用using System.Drawing;

二、在窗体中声明两个变量

private float X;

private float Y;

三、窗体的两个事件

private void 窗体名称_Load(object sender, EventArgs e)
        {           
            this.Resize += new EventHandler(窗体名称_Resize);
 
            X = this.Width;
 
            Y = this.Height;
 
            类.Main.SetTag(this);
 
            窗体名称_Resize(new object(), new EventArgs());
            this.WindowState = FormWindowState.Maximized;
        }
        private void 窗体名称_Resize(object sender, EventArgs e)
        {
            if (X == 0)
            {
                窗体名称_Load(new object(), new EventArgs());
            }
            else
            {
                float newx = (this.Width) / X;
 
                float newy = this.Height / Y;
 
                类.Main.SetControls(newx, newy, this);
            }
        }

  注:如果是子窗体,窗体要设置属性MaximizeBox=True,MinmizeBox=True,Windowstate=Normal

posted @   tyxajh  阅读(344)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示