'How to set the form resolution for each screen in C#?

I made a project in C# Form with

FormBorderStyle=FormBorderStyle.None

Resolution = 1920 x 1080.

But, this project is set for 1080p only and takes it offscreen at 720p. How can I code this form (including the components inside) so that it fits on any screen? If it needs to grow, it will grow, if it needs to shrink, it will shrink, but all the components should also move accordingly, so they are always visible on the form.

As I said, I don't use border in my project.



Solution 1:[1]

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 configured 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 are scaled. To rescale, you can apply changes to both the Location and Size properties in a foreach loop. I recommend defining a seperate method for this:

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1