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