Home > Articles > Programming > Windows Programming

Like this article? We recommend

Configuring Your Form for Resizing

Every time I built a resizable form in Visual Basic 6.0 (which includes every form I built except for the simplest of dialog boxes), I had to write code into the form's Resize event.

I had to decide how I wanted each control to adjust to the new size of the form, what size was too small for my interface to be usable, and I had to remember to check if the form had been minimized before trying to do any resizing. This code was not particularly hard to write, and after 50 or 60 forms I could do it without much thought, but it still took time and effort for every form I created. In Windows forms, a variety of features have come together to allow you to configure your controls for auto-resizing without having to write a single line of code. By combining the docking and anchoring features with the careful use of panels, you can set your form up to resize in almost any way you can imagine. If you add in the auto-scroll feature, you can even have parts of the form that do not resize at all, but instead extend right off the visible area of the form.

Using the Layout Event in Windows Forms

This section is all about avoiding the code you used to have to write into your Resize event handler, but even if you did write code, it wouldn't be in the same event handler in .NET. A new event, Layout, is available in Windows forms, and if you need to write code that adjusts the form after a resize, the Layout event is the best place for it.

The following sections explain how each of these three features works and how the use of panels can increase your flexibility of control arrangement. Once you have learned about all the features, the chapter will detail a few of the more common form layout scenarios, showing you how to set them up for proper resizing.

Using Docking to Handle Resizing

Docking windows and toolbars have been in use for quite some time, so the general concept is not new; a docked item is attached to one of the edges of its container (such as a form). Consider a form that contains only a single ListBox control. If you set the ListBox's Dock property to Left (see Figure 3.5), the height of the control will be fixed to the height of the form's client area (causing the list box to fill the form from top to bottom), while the position of the control will be locked to the left side of the form. The only thing you can change about the size of the list box at this point is its width, controlling how far out from the left side it extends. Docking to the right is essentially the same; the list box becomes attached to the right side of the form, but you can still change its width as desired. Docking to the top or bottom will cause the width to be fixed to fill the width of the form, but the height of the control can still be modified.

Figure 3.5Figure 3.5 Docking a control to the left makes it stick to the left side, while filling the vertical space of the container.

In addition to docking to one of the four sides, controls also support a fifth (sixth if you count None for no docking) docking setting, Fill. If you set the Dock property to Fill, that control becomes attached to all four sides of the container, adjusting itself automatically as the form is resized. You cannot adjust any size or position settings for a control that has been docked to fill the container.

Remember that you are docking the control to its container, which in this example is the Form, but could be a container control such as a GroupBox or Panel. This flexibility leads to more layout options, as you will see later in the section on "Using Panels."

The container (form, panel, or other type of container control) has a DockPadding property, which allows it to specify a certain amount of padding between it and docked controls. The padding values can be specified individually for the four sides of the container, or an overall padding value that applies to all of the sides at once. If a container has specified a DockPadding value of 10, for example, a control docked to the left will be positioned 10 pixels away from the left edge. The DockPadding setting is great for creating a more visually pleasing user interface as it results in a border around the form while still enabling the automatic resizing of docked controls (see Figure 3.6).

Figure 3.6Figure 3.6 DockPadding allows you to dock, without sacrificing a bit of white space around the edge of your controls.

Docking gets a little more complicated when multiple docked controls are involved. If you dock more than one control to the same edge, the second control will dock alongside the first instead of directly to the container. Going back to the example with the ListBox on a form, you can try multiple docked controls to see what happens. If you docked the ListBox to the bottom and then added a new DataGrid to the form, setting its Dock property also to Bottom, you would have produced an interface similar to Figure 3.7, where the ListBox appears below the DataGrid.

Figure 3.7Figure 3.7 Multiple controls docked to the same side will stack instead of overlap.

Both of the controls are docked to the form and will resize as the form is resized. If you have controls docked to one or more sides of your container, and then you set another control's Dock property to Fill, the control set to Fill will be automatically sized to use all of the remaining area of the container. If you have multiple controls docked on a form, you might want to use the Splitter control. Splitter is a special Windows Forms control that, when docked between two other controls, allows you to resize the two controls at runtime. Using the Splitter control and a few other key controls, you can create a standard Explorer view form in a matter of minutes.

To add a splitter to your form, you need to be careful of the order in which you add your controls. Try adding a ListBox to an empty form, and docking it to the left. Then add a splitter control, and dock it to the left as well (it is by default). Finally, add a DataGrid control, dock it to the left as well, or set its dock property to Fill, and you will have a working example of using a splitter!

A little confusing? It can appear very complex, but the best bet is to try it out on your own, adding a variety of controls to a blank form and playing around with the various Dock/DockPadding settings.

Anchoring as an Alternative Resizing Technique

After docking, this has to be the coolest layout feature. Anchoring is a little simpler than docking, but it can be a powerful tool. Using a graphical property editor (see Figure 3.8), you can set the Anchor property for a control to any combination of Top, Left, Bottom, and/or Right.

Figure 3.8Figure 3.8 The property editor for anchoring is a nice little graphical control.

To anchor a control to a specific side means that the distance between the control and that side of its container becomes fixed. Therefore, if you anchor a control to a specific side and then resize the form, the control's distance from the anchored side(s) will not change. To maintain a constant position relative to one or more sides of your container, the control might have to be resized when the form's size changes.

By default, controls are anchored to the top and left, which makes them behave exactly as controls did in previous versions of Visual Basic. When you resize the form, they do not move or resize. If you want to create a TextBox that grows as you make your form wider, you can anchor it to the top, left, and right sides. If you want the TextBox to grow in height as well as width, anchor it to the bottom as well. Figure 3.9 shows a form with some anchored controls, and Figure 3.10 shows what happens when that form is resized. You will see a few more examples of how anchoring can be used to lay out your form in the samples throughout the rest of this book.

Figure 3.9Figure 3.9 Anchored controls maintain a fixed distance between themselves and the container edge(s) they are anchored to.

Figure 3.10Figure 3.10 As the form changes size, the controls move and resize automatically.

AutoScrolling Forms

Docking and anchoring are designed to resize your controls when the form is resized, but resizing the contents of your form is not always appropriate. In some cases there is a minimum size at which your form is usable, so resizing below that needs to be avoided. There are also situations when the content on your form is a fixed size, making resizing inappropriate. Windows forms provides a few additional features to allow you to deal with these situations. Forms have minimum/maximum height and width properties (allowing you to constrain resizing to a specific range of sizes) and the AutoScroll feature. AutoScroll allows a form to be resized by the users, but instead of shrinking the controls on the form, scroll bars appear to allow the users to view the entire form area even if they have resized the window. The form shown in Figure 3.11 is a perfect candidate for AutoScroll; it contains a large number of controls and buttons and cannot be resized using docking or anchoring.

Figure 3.11Figure 3.11 This form would be hard to resize, so the solution is to allow users to scroll.

If the user were to resize this form, making it smaller than the area required for all of its controls, the AutoScroll feature of Windows forms will save the day by adding horizontal and/or vertical scroll bars as required (see Figure 3.12).

Figure 3.12Figure 3.12 AutoScroll automatically adds scroll bars when the form becomes small enough to hide any part of any of the controls on the form.

In addition to the AutoScroll property, which you set to True to enable auto scrolling, there are two other properties, AutoScrollMargin and AutoScrollMinSize, that are used to configure exactly how scrolling occurs.

Using Panels

Panels enhance all of the other layout features discussed so far because they can act as a container for other controls, much like a form does. Because they are containers, panels have their own DockPadding property and all of the auto-scroll features described for forms. A control can be placed into a panel and anchored to the bottom-right corner of that panel, while the panel itself was docked or anchored to a specific location on a form. By combining panels with forms, you can design more complicated layouts that still support resizing. Panels are used in several of the examples in the next section.

Some Common Resizing Scenarios

Now that you have been told what docking, anchoring, and auto-scrolling are, here are a few forms that demonstrate using the new layout features.

A Standard One-Large-Control Dialog Box

A large control, such as TextBox, ListBox, or DataGrid, needs to resize properly on a Form with two buttons (OK and Cancel), as shown in Figure 3.13.

Figure 3.13Figure 3.13 Allowing the users to resize your form makes your application work better on a range of screen sizes.

If it were not for those two buttons, docking would be a possible answer, but anchoring saves the day here. Assuming a desired border around the form's contents of 10 pixels:

  • Position the large control with its top, left, and right edges 10 pixels in from the corresponding form edges. Note that you don't have to be exact about these positions, anchoring will lock the control in whatever place you put it. A precise border is just for aesthetics.

  • Add your two buttons to the bottom of the form, placing their bottom edge 10 pixels up from the bottom of the form. The right edge of one button should be 10 pixels in from the right edge of the form. Place the other button so that its right edge is five pixels away from the left edge of the first button.

  • Adjust the height of the large control so that its bottom edge is 10 pixels from the top of the two buttons.

  • Now, set the large control's Anchor property to "Top, Bottom, Left, Right" and both buttons' Anchor property to "Bottom, Right".

A Long List of Questions

You have a long list of questions that must be answered before a user can submit an order, and additional questions keep being added. There also needs to be an OK and Cancel button on the form; OK to move onto submitting the order, and Cancel to close the form and cancel the order.

AutoScroll is the key for this layout, either for the entire form or for a panel, depending on whether you want to keep the OK and Cancel buttons visible at all times or if you want the user to have to scroll down to find them.

  • For the first option (Figure 3.14), where you want the buttons to be visible at all times, set up your form just like in Example 3.1, but use a Panel control as the large control.

  • Figure 3.14Figure 3.14 A panel allows you to restrict which parts of the form scroll and which parts are always visible.

  • Set the panel's AutoScroll property to True and then place all of your individual questions into the panel.

  • For the second option (Figure 3.15), set the Form's AutoScroll property to True and place all of your questions onto the form.

  • Figure 3.15Figure 3.15 You can use the entire form surface for your scrolling area.

  • Add your OK and Cancel buttons at the very bottom of your form below all of the questions.

A Multi-Column Form

You have a form with multiple columns of text boxes, each with associated labels, a single large text box, and the OK and Cancel buttons at the bottom (see Figure 3.16).

Figure 3.16Figure 3.16 Multiple columns are trickier to resize.

This gets a little trickier because of the two columns at the top of the form, but panels can make it all work out.

  • Create a panel (mainPanel) that is tall enough to contain all of your controls for the top section of the form.

  • Create two more panels (rightPanel and leftPanel) and place them in the first panel you created.

  • Select one of new panels (rightPanel) and make its Dock property equal to Right; make the other panel's Dock property equal to Fill.

  • Now, leftPanel will always fill the space not taken by rightPanel, but there is no way (in the designer) to force those two panels to equally share the available space. Instead you have to go to code.

  • View the code for your form, and then select mainPanel from the object drop-down list (left side) and Layout from the event drop-down list (right side). Enter the code from Listing 3.16, assuming your panel names are mainPanel, rightPanel, and leftPanel, into the Layout event handler.

  • Listing 3.16 Using Code to Make Two Panels Share the Available Space

    Private Sub mainPanel_Layout( _
        ByVal sender As Object, _
        ByVal e As System.Windows.Forms.LayoutEventArgs) _
          Handles mainPanel.Layout
      rightPanel.Width = mainPanel.Width \ 2
    End Sub

Note that I used the Layout event, which is a new event in Windows forms that was not available in Visual Basic 6.0. In Visual Basic 6.0, I would have used the Resize event, but Layout is actually more precise as it occurs when the position and size of controls within a container might need adjusting, as opposed to occurring upon every resize of the form. If a form were set to AutoScroll, for example, the Resize event would fire whenever the form was resized (as it should), but the controls inside the form would not need to be rearranged.

An Explorer-Style Application

You are attempting to produce an interface in the format of the Windows Explorer, Outlook, and other applications. This interface will have a TreeView along one side of the form and a ListView on the other, and have the capability to move the dividing line between the two controls to resize them (see Figure 3.17).

Figure 3.17Figure 3.17 The standard Explorer style of form layout.

This style of layout is easy to accomplish with the new features of Windows forms, but the specific order in which you add items to your form is important.

  • Starting with a blank form, add a TreeView control and set its Dock property to Left.

  • Add a Splitter control; it will automatically dock to the left and take its place along the right side of the TreeView.

  • Add a ListView control and set its Dock property to Fill.

That's it. The ListView will fill whatever space isn't being used by the TreeView and the Splitter will allow you to adjust the relative size of the two areas.

That is all of the sample resizing scenarios covered in this chapter, but that certainly is not the extent of layouts that can be created.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020