简体   繁体   English

如何在C#中调整窗体的大小以包含其控件?

[英]How to re-size a form to contain its controls in C#?

截图

I am new to C# and I am using windows forms. 我是C#的新手,正在使用Windows窗体。

As shown in screenshot I have Form1 which has flowLayoutPanel1 and ButtonCancel . screenshot所示,我有Form1 ,其中有flowLayoutPanel1ButtonCancel

When Form1 loads, number of buttons are added into the flowLayoutPanel1 (the number of buttons is changing and it is not fixed). 加载Form1时, buttons数量会添加到flowLayoutPanel1 (按钮的数量正在更改,并且不是固定的)。

 private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i <= 1; i++)
            {

            Button btn = new Button();
            btn.Name = i.ToString();  
            btn.Width = 104;
            btn.Height = 63;
            btn.FlatStyle = FlatStyle.Popup;              
            flowLayoutPanel1.Controls.Add(btn);

            }
 }

Problem: 问题:

The problem is that there is a gap that I want to remove, to do that I have to reduce Form1 Height according to the number of the added buttons but I do not know how to resize Form1 Height based on the number of added buttons . 问题是我要消除一个缝隙,为此我必须根据所添加buttons的数量减小Form1 Height,但是我不知道如何根据所添加buttons的数量来调整Form1 Height的大小。

For example, if 2 buttons are added I want Form1 to shrink to fit the 2 buttons and if 8 buttons are added I want Form1 to expand to fit the 8 buttons without leaving gap. 例如,如果添加了2个buttons ,我希望Form1缩小以适合2个buttons ,如果添加8个buttons ,我希望Form1扩展以适合8个buttons而又不留间隙。

Is there any Form property allows Form1 to expand and shrink according to the number of added buttons ? 是否有任何Form property允许Form1根据添加的buttons数量进行扩展和收缩?

Thank you 谢谢

The following should work 以下应该工作

  • Put a TableLayoutPanel with one column and two rows on the Form 将具有一列和两行的TableLayoutPanel放在Form上
  • Set the Dock -property of the TableLayoutPanel to Fill TableLayoutPanelDock属性设置为Fill
  • Set the Size-Type of the first row of the TableLayoutPanel to Percent -> 100% TableLayoutPanel第一行的Size-Type设置为TableLayoutPanel > 100%
  • Set the Size-Type of the second row of the TableLayoutPanel to Absolute -> 63 Pixel TableLayoutPanel第二行的Size-Type设置为Absolute-> 63 Pixel
  • Put the FlowLayoutPanel inside the first row FlowLayoutPanel放在第一行中
  • Put the Cancel- Button inside the second row 将取消Button放在第二行内
  • Set the AutoSize -property of Form , TableLayoutPanel and FlowLayoutPanel to True FormTableLayoutPanelFlowLayoutPanelAutoSize属性设置为True
  • Set the AutoSizeMode -property of Form , TableLayoutPanel and FlowLayoutPanel to GrowAndShrink FormTableLayoutPanelFlowLayoutPanelAutoSizeMode属性设置为GrowAndShrink

如果启用对接,它将自动调整大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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