Resizing a C# Control

Resizing a C# control as the entire form is resized is very easy actually. All you have to do is set up a resize event for the form and inside the event tell the control to update its size according to the form’s size.

Bellow is an example on how to resize a picture box when the form is resized. First add a picture box to your form.

public Form1()
{
InitializeComponent();
//the size of the form
this.Size = new Size(400, 400);
//the location of the pictureBox's top right corner
pictureBox1.Location = new Point(10, 10);
//the width and height of the picture box.
//ClientSize gets the width and height of the form's inner area
//from the ClientSize Width and Height we substarct 20
//(twice the gap from the left side)
pictureBox1.Width = ClientSize.Width - 20;
pictureBox1.Height = ClientSize.Height - 20;
}

private void Form1_Resize(object sender, EventArgs e)
{
//while resizing we constantly update the width and height of the pictureBox
pictureBox1.Width = ClientSize.Width - 20;
pictureBox1.Height = ClientSize.Height - 20;
}

No comments:

Post a Comment