Title: Set form client size in C#
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 200x300 or 300x200 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 200x300 pixels or 300x200 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 200x300 or 300x200 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.
Download the example to experiment with it and to see additional details.
|