WinForm Responsive Layout Design Practice

Source: Internet
Author: User
Tags response code

Introduction

Creating a responsive WinForm application is not that simple. Responsive layout, where I'm referring to the usability of the application at different screen resolutions. For WinForm applications, we need to explicitly adjust the size and repositioning of the controls based on the resolution. Although there are related practical applications when using WPF, by using docking and anchoring of controls, or by using methods such as panels, this article provides a different way to apply responses to WinForm applications.

Background

I had a problem with a simple game I designed myself: I designed a machine with a resolution of 1920x1080, but when I tried to play on my laptop, I found the application boundary running outside the screen. It is necessary for the program to adapt to different resolutions of the device, rather than let the user to adapt to the program. So I made improvements to the code.

Technology

In fact, there is no technology to say, just a little trick. We use two constants to preserve the screen resolution at design time, which we call design-time resolution. Thus, whenever the application is run, it gets a multiplication factor, which is actually a scale factor that is obtained by dividing the current resolution by the design-time resolution. All controls on the form are passed to the class object for scaling and resizing.

Code The Responsive Class-responsive.cs

To create a class Responsive.cs, add 5 variables.

float WIDTH_AT_DESIGN_TIME = (float)Convert.ToDouble                             (ConfigurationManager.AppSettings["DESIGN_TIME_SCREEN_WIDTH"]);float HEIGHT_AT_DESIGN_TIME = (float)Convert.ToDouble                              (ConfigurationManager.AppSettings["DESIGN_TIME_SCREEN_HEIGHT"]);Rectangle Resolution;float WidthMultiplicationFactor;float HeightMultiplicationFactor;

The design-time screen resolution is saved in the App. config file.

<add key ="DESIGN_TIME_SCREEN_WIDTH" value="1920"/><add key ="DESIGN_TIME_SCREEN_HEIGHT" value="1080"/>

When an instance of a class is created, the current resolution is provided to the constructor. The Setmultiplicationfactor () method of the class is then called. This method obtains the scaling factor by dividing the current resolution by the design time resolution.

public Responsive(Rectangle ResolutionParam){    Resolution = ResolutionParam;}public void SetMultiplicationFactor(){    WidthMultiplicationFactor = Resolution.Width / WIDTH_AT_DESIGN_TIME;    HeightMultiplicationFactor = Resolution.Height / HEIGHT_AT_DESIGN_TIME;}

For example, the application is designed at 1920x1080 resolution. If this application is running on a computer with a resolution of 1024x768, then Widthmultiplicationfactor and heightmultiplicationfactor are changed as follows:

WidthMultiplicationFactor = 1024/1920 = 0.533HeightMultiplicationFactor = 768/1080 = 0.711

Finally, there are two overloaded methods that provide the final method for the application control (optimal size, location, and font size) for the response solution.

public int GetMetrics(int ComponentValue){    return (int)(Math.Floor(ComponentValue * WidthMultiplicationFactor));}public int GetMetrics(int ComponentValue, string Direction){    if (Direction.Equals("Width") || Direction.Equals("Left"))        return (int)(Math.Floor(ComponentValue * WidthMultiplicationFactor));    else if (Direction.Equals("Height") || Direction.Equals("Top"))        return (int)(Math.Floor(ComponentValue * HeightMultiplicationFactor));    return 1;}

For example, if there is a control with width = 465, height = 72, left = 366, top =41, and font size =40, then the method returns the recommended size, location, and font size:

Width = 465 * 0.533 = 248Height = 72 * 0.711= 51Left = 366 * 0.533= 195Top = 41 * 0.711= 29Font-size = 40 * 0.533 = 21

In fact, these methods return scaled controls with size, position, and font size, and these values are the best values to show.

Using Responsive Class

What we need is simply to create the object of this class in any form that needs to be responded to. The current resolution is provided in the constructor, and the subsequent work is to establish the desired multiplication factor.

Responsive ResponsiveObj;ResponsiveObj = new Responsive(Screen.PrimaryScreen.Bounds);ResponsiveObj.SetMultiplicationFactor();

After that, all the controls for the form are passed one-by-step to resize and reposition in the form's Load event. This call is done in the following code. What it does is to first position the form to the center of the screen. Here I set a calibration constant (30) to add controls for the best vertical position, which may vary by developer. After that, each control of the form is repositioned, resized, and re-calibrated to the font size.

private void ResponsiveForm_Load(object sender, EventArgs e){    Width = ResponsiveObj.GetMetrics(Width, "Width");           // Form width and height set up.    Height = ResponsiveObj.GetMetrics(Height, "Height");    Left = Screen.GetBounds(this).Width / 2 - Width / 2;        // Form centering.    Top = Screen.GetBounds(this).Height / 2 - Height / 2 - 30;  // 30 is a calibration factor.    foreach (Control Ctl in this.Controls)    {        Ctl.Font = new Font(FontFamily.GenericSansSerif,                    ResponsiveObj.GetMetrics((int)Ctl.Font.Size), FontStyle.Regular);        Ctl.Width = ResponsiveObj.GetMetrics(Ctl.Width, "Width");        Ctl.Height = ResponsiveObj.GetMetrics(Ctl.Height, "Height");        Ctl.Top = ResponsiveObj.GetMetrics(Ctl.Top, "Top");        Ctl.Left = ResponsiveObj.GetMetrics(Ctl.Left, "Left");    }}
Example

Here is a very simple form that contains a data gird, a label, a textbox, and a button. The images below are intercepted at three different resolutions. The following is intercepted at 1920x1080 resolution:

The following is intercepted at 1360x768 resolution:

The following is intercepted at 1024x768 resolution:

In fact, the form looks the same at different resolutions by narrowing/widening and repositioning the control to the optimal level.

Code adjustment

As we have done with vertical center positioning, we may need to set some parameters to adjust the entire layout.

It is also recommended that developers try to look at different resolutions to see how the form looks, to make sure that all controls are visible, and to correctly position the screen as expected.

In addition, for a simple form, this is a common method, which assumes that all controls on the form have these properties---width, height, left, top, and font size. However, this is not the case in reality. There are some form controls that do not have all of these properties. For example, the picture box does not have a font-size property. Therefore, running the code will result in a run-time exception if it is not explicitly handled in such a case. The purpose of this article is to introduce this approach, which developers need to calibrate according to the actual situation. The recommended method is as follows:

private void Responsiveform_load (object sender, EventArgs e) {width = responsiveobj.getmetrics (width, "width");    Form width and height set up.    Height = responsiveobj.getmetrics (height, "height"); left = Screen.getbounds (this).        WIDTH/2-WIDTH/2;    Form centering. Top = Screen.getbounds (this).  HEIGHT/2-HEIGHT/2-30;    is a calibration factor. foreach (Control Ctl in).             Controls) {if (Ctl is PictureBox) {ctl.width = Responsiveobj.getmetrics (Ctl.width, "Width");            Ctl.height = Responsiveobj.getmetrics (Ctl.height, "Height");            Ctl.top = Responsiveobj.getmetrics (Ctl.top, "Top");        Ctl.left = Responsiveobj.getmetrics (Ctl.left, "left"); } else {ctl.font = new Font (Fontfamily.genericsansserif, respons            Iveobj.getmetrics ((int) Ctl.Font.Size), fontstyle.regular); Ctl.width = Responsiveobj.getmetrics (Ctl.width, "Width");            Ctl.height = Responsiveobj.getmetrics (Ctl.height, "Height");            Ctl.top = Responsiveobj.getmetrics (Ctl.top, "Top");        Ctl.left = Responsiveobj.getmetrics (Ctl.left, "left"); }    }}

The code may be adjusted based on the salesperson's needs and the properties of the control. In addition, you may need to introduce more overloaded methods for different control types.

Other

As mentioned earlier, there are other methods, such as using WPF, using anchoring/docking, and so on, which is a smarter option. If there are thousands of controls on the form, you may experience load delays. However, this delay is not a problem for a processor that is now running fast. This method only performs a call operation once the form is loaded, so it does not cause a fatal performance degradation problem.

End

Creating a responsive WinForm application that automatically resizes according to the machine's runtime resolution, repositions the font size and re-calibrates the font size is a developer-oriented approach. Simply add the class to your project, set the design-time resolution in the App. Config file, and then add the response code in the form's Load event. So easy!

WinForm Responsive Layout Design Practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.