Change form size at runtime in C#

前端 未结 6 1732
傲寒
傲寒 2021-01-01 19:32

How can I change window form size at runtime?

I saw examples, but every one requires Form.Size property. This property can be set like here: http://msdn.microsoft.co

相关标签:
6条回答
  • 2021-01-01 19:51

    As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.

    Example Bellow:

    private void SetDefaultWindowSize()
    {
       int sizeW, sizeH;
       sizeW = 180;
       sizeH = 100;
    
       var size = new Size(sizeW, sizeH);
    
       Size = size;
       MinimumSize = size;
    }
    
    private void SetNewSize()
    {
       Size = new Size(Width, 10);
    }
    
    0 讨论(0)
  • 2021-01-01 19:54

    You can change the height of a form by doing the following where you want to change the size (substitute '10' for your size):

    this.Height = 10;
    

    This can be done with the width as well:

    this.Width = 10;
    
    0 讨论(0)
  • 2021-01-01 19:56

    You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:

    button1_Click(object sender, EventArgs e)
    {
        // This will change the Form's Width and Height, respectively.
        this.Size = new Size(420, 200);
    }
    
    0 讨论(0)
  • 2021-01-01 19:59

    If you want to manipulate the form programmatically the simplest solution is to keep a reference to it:

    static Form myForm;
    
    static void Main()
    {
        myForm = new Form();
        Application.Run(myForm);
    }
    

    You can then use that to change the size (or what ever else you want to do) at run time. Though as Arrow points out you can't set the Width and Height directly but have to set the Size property.

    0 讨论(0)
  • 2021-01-01 19:59

    Something like this works fine for me:

    public partial class Form1 : Form
    {
        Form mainFormHandler;
    ...
    }
    
    private void Form1_Load(object sender, EventArgs e){
        mainFormHandler = Application.OpenForms[0];
       //or instead use this one:
       //mainFormHandler = Application.OpenForms["Form1"];
    }
    

    Then you can change the size as below:

    mainFormHandler.Width = 600;
    mainFormHandler.Height= 400;
    

    or

    mainFormHandler.Size = new Size(600, 400);
    

    Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

    0 讨论(0)
  • 2021-01-01 20:11

    In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.

    public partial class Form1 : Form
    {
        public void ChangeSize(int width, int height)
        {
            this.Size = new Size(width, height);
        }
    }
    
    0 讨论(0)
提交回复
热议问题