Wednesday, August 26, 2009

Change Control Size Automatically with Form Size Change

Here is how you can change a form control size automatically when the form size is changed by user.
Declare a class variable that will hold the value of the current form size, and set its value in the contructor.

Size curSize;
public Form1()
{
InitializeComponent();
curSize = this.Size;
}

To capture form size change, use the ClientSizeChanged event handler with the following code:

private void Form1_ClientSizeChanged(object sender, EventArgs e)
{
    int heightDif = Size.Height - curSize.Height;
    int widthDif = Size.Width - curSize.Width;
    yourControlName.Height += heightDif;
    yourControlName.Width += widthDif;
    //store the current size until the next time this event is raised
    curSize = this.Size;
}