简体   繁体   中英

Adjust controls to match form resize in Visual Studio C# 2019?

Normally, when I shrink my form, it just covers stuff up. How do I make it so that the content adjusts position when the form is resized?

The only answers to this question are from 9-10 years ago and refer to properties I can't find.

Edit: I think I might not be using winforms, the specific project type is "Windows Forms App (.NET Framework), is that not winforms?

You can create a new class to resize the position of the control when the form is resized.

public partial class Form1 : Form
    {

        AutoSizeFormClass asc = new AutoSizeFormClass();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }
    }
    class AutoSizeFormClass
    {  
        public struct controlRect
        {
            public int Left;
            public int Top;
            public int Width;
            public int Height;
        }
        public List<controlRect> oldCtrl;
        public void controllInitializeSize(Form 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);
                }

        }
        public void controlAutoSize(Form mForm)
        { 
            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;
            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); 

                ctrlNo += 1;
            }
        }

    }

Tested result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM