You would first have to find out what the resolution is of your screen.
If you have multiple screens, by default the Form
will appear on the primary screen, which is Screen.PrimaryScreen
.
This has the two properties you will need: Bounds.Width
and Bounds.Height
. With these you can change the ClientSize
to fit your screen.
private double screenWidth = Screen.PrimaryScreen.Bounds.Width;
private double screenHeight = Screen.PrimaryScreen.Bounds.Height;
private void FitWindowFormToScreen() {
this.ClientSize = new Size
( Convert.ToInt32(screenWidth),
Convert.ToInt32(screenHeight)
);
}
To also scale the components
You first need to calculate the ratio of the screen size to the original Form
size, at which you designed the layout. The denominators may just be expressed as numbers, because you only need to define it once.
double xShift = screenWidth / 816;
double yShift = screenHeight / 489;
These can then be used as the factor by which all controls on the Form
are scaled. To rescale both the Location
and Size
properties in a foreach
loop, I recommend defining a seperate method:
private void ScaleLayout(Control container) {
foreach (Control control in container.Controls) {
control.Location = new Point
( Convert.ToInt32(control.Location.X * xShift),
Convert.ToInt32(control.Location.Y * yShift)
);
control.Size = new Size
( Convert.ToInt32(control.Size.Width * xShift),
Convert.ToInt32(control.Size.Height * yShift)
);
}
}
This function takes a parameter for a reason; controls that are inside of container controls like GroupBox
or TabControl
objects are not affected. So, you can use a recursive call like this:
if (control.HasChildren) {
ScaleLayout(control);
}
To call this method, simply do:
ScaleLayout(this);