简体   繁体   English

根据控件可见性C#.Net动态自动调整窗口大小

[英]Auto re-size windows form dynamically according to the control visibility, C#.Net

While creating a windows form application, initially I am keeping all the controls like Button, TextBox, Label invisible. 在创建Windows窗体应用程序时,最初我保持Button,TextBox,Label等所有控件都不可见。 Once, the user do a proper activity like select correct directory then the next control appears (In general, the user won't be having much freedom but to give a correct directory). 一旦用户做了正确的活动,比如选择正确的目录,则出现下一个控件(通常,用户不会有太大的自由,而是提供正确的目录)。 I know, there is no sense keeping other control invisible all the time but I want to do it as my learning process. 我知道,没有任何意义保持其他控件不可见,但我想把它作为我的学习过程。

Now, the question is, how do I make the form change it's size each time a new control appears. 现在,问题是,每次出现新控件时,如何使表单更改其大小。

eg at start only one TextBox and Browse button are visible. 例如,在开始时,只有一个TextBox和Browse按钮可见。 Here the windows form should scaled to the visible controls only. 这里的窗体应仅缩放到可见控件。 Then once user gives a proper directory path and the program recognizes it, next control like a button and a richTextBox will show up and the form then should change itself dynamically to fit new controls. 然后,一旦用户提供了正确的目录路径并且程序识别出它,就会显示下一个控件,如按钮和richTextBox,然后表单应该动态更改以适应新的控件。

Thanks for help, 感谢帮助,

This is all simple enough, you can alter the visibility of a control with the Visible property, and change the size of your form by altering the Height and Width properties of the form. 这很简单,您可以使用Visible属性更改控件的Visible性,并通过更改窗体的“ Height和“ Width属性来更改窗体的大小。

If you create a form named Form1 , add two buttons named button1 and button2 and copy and paste the following code, this will demonstrate both resizing the form and changing the visibility of controls. 如果您创建名为Form1的表单,请添加两个名为button1button2的按钮,并复制并粘贴以下代码,这将演示调整表单大小和更改控件的可见性。

button2 gets set to invisible as the form loads, and the width and height get set to 100px each. 当表单加载时, button2被设置为不可见,并且宽度和高度各自设置为100px。 Whenever button1 is pressed, the form is resized and button2 is set to visible: 每当按下button1时 ,表单都会调整大小并且button2设置为可见:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Visible = false;

            Width = 100;
            Height = 100;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Width = 200;
            Height = 200;
            button2.Visible = true;
        }
    }
}

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

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