Set form client size in C#

[Set form client size]

This example shows how to use the ClientSize property to set form client size. Many programmers know that a form’s ClientSize property gives the size of the area inside the form’s borders, but few know that you can set ClientSize. When you set ClientSize, the form resizes itself so it holds its borders and title bar and still has the desired interior size.

When you check the 200×300 or 300×200 radio button, the following event handler executes.

// Change the size.
private void rad200x300_CheckedChanged(object sender, EventArgs e)
{
    if (rad200x300.Checked) ClientSize = new Size(200, 300);
    else ClientSize = new Size(300, 200);

    Refresh();
}

This code sets the form’s ClientSize property to either 200×300 pixels or 300×200 pixels. It then calls the form’s Refresh method to raise the Paint event, which is handled by the following event handler.

// Draw a diamond of the appropriate size.
private void Form1_Paint(object sender, PaintEventArgs e)
{
    int hgt, wid;
    if (rad200x300.Checked) { hgt = 300; wid = 200; }
    else                    { hgt = 200; wid = 300; }
    Point[] pts =
    {
        new Point(wid / 2, 0),
        new Point(wid, hgt / 2),
        new Point(wid / 2, hgt),
        new Point(0, hgt / 2),
    };

    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.DrawPolygon(Pens.Blue, pts);
}

This event handler draws a diamond that is either 200×300 or 300×200 to show the form’s interior size.

The result is the form resizes itself and then draws a diamond to exactly fit the desired ClientSize.

   

This entry was posted in controls, forms and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *