【问题标题】:Adjust controls to match form resize in Visual Studio C# 2019?调整控件以匹配 Visual Studio C# 2019 中的表单调整大小?
【发布时间】:2020-05-04 16:27:37
【问题描述】:

通常,当我缩小表格时,它只会掩盖东西。如何在调整表单大小时调整内容的位置?

这个问题的唯一答案是 9 到 10 年前的,指的是我找不到的房产。

编辑:我想我可能没有使用winforms,具体的项目类型是“Windows Forms App (.NET Framework),那不是winforms吗?

【问题讨论】:

  • 这能回答你的问题吗? Dock, Anchor and Fluid layouts in Windows Forms Applications - 是的,大约 9 岁,但仍然如此。您确定您使用的是 Winforms 吗?你找不到什么房产?哦,对了,TableLayoutPanelFlowLayoutPanel 是控件。
  • “这个问题的唯一答案是 9-10 年前” 同时,更现代的 GUI 框架,如 WPF 和不同形式的应用程序(单页 Web 应用程序,例如例如...)已经变得更加普遍。 WinForms 是一项相当古老的技术,因此对它的任何问题和答案都可能已经过时了。
  • 如果您坚持使用 WinForms,那么对于比“hello world”应用程序更复杂的应用程序,您需要学习如何使用TableLayoutPanel
  • 从这些cmets中,我感觉我用的不是winforms。
  • 是的,就是 WinForms。在设计器中,如果单击 TextBox 控件,您应该会看到名为 Anchor 或 Dock 等的属性。适当地设置它们。

标签: c# visual-studio-2019


【解决方案1】:

您可以创建一个新类来调整窗体大小时控件的位置。

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;
            }
        }

    }

测试结果:

【讨论】: