[Msdn digest] Windows Forms Layout

Source: Internet
Author: User
Windows Forms Layout

Chris sells
Sells brothers Consulting

December 5, 2002

Summary:
Chris sells discusses how controls are scaled and arranged on a form,
And how the scaling and arrangement features are used to meet the needs
Of different users with respect to system font size and the size of
Data being entered. (8 printed pages)

Download the winforms12102002.exe sample file.

After
All those heavy threading and Security pieces, I thought I 'd go back
Into some of the basics of one of the most compelling new features in
Windows Forms-how controls are scaled and arranged on a form. These
Scaling and arrangement features are used to meet the needs
Different users with respect to system font size and the size of
Data being entered.

Form auto-Scaling

For example, if you lay out a form with system font size set to normal (96 DPI) inDisplay
Control Panel, what happens when your users are using large (120 DPI)
Or one of the custom settings? You 'd certainly want a form like figure
1 To show properly at all font sizes.

Figure 1. An example form at normal size Fonts

If you perform the actual test by changing from normal to Large fonts inDisplay
Control Panel (requiring a restart under Microsoft Windows XP), you'll
Be pleased to see that your form at this new font size looks like
Figure 2 without recompiling your application.

Figure 2. The example form at large size Fonts

The secret to making this work is a form property calledAutoscale. When a form is first loaded, and ifAutoscaleIs set to true (the default), it uses another property calledAutoscalebasesize.
This property is set by the designer and specifies the average width
And height of Characters in the form's font. The default font, 8.25pt
MS sans serif under Windows XP normal fonts, has an average width and
Height of 5x13. This information will be encoded intoInitializecomponentFunction like so:

 
This. autoscalebasesize = new size (5, 13 );

Under Large fonts, the default font will be 7.8pt MS
Sans serif, but the average width and height of the font has now
Increased to 6x15 (which is why they call it "large" fonts). At Load
Time, the form will notice the difference between the scale it was
Designed with and the current scale by callingForm. getautoscalesize
And adjust the height and width of itself and its controls along
The positions of the controls. This keeps the feel of the form roughly
The same, regardless of the system font settings.

Anchoring

Of
Course, scaling for system font settings is not all of the work that
Needs to be done to make your form adjusts itself to your users 'whims.
For example, if a user of our current example wants to enter a longer
String into the text box, they may attempt to widen the form to do so,
As shown in figure 3.

Figure 3. All controls anchored top, left

Unfortunately,
The user isn' t likely to be happy when the form takes up more room,
The contained controls do not. Ideally, we 'd like the text box
Expand as the form expands, which can be achieved like so:

 
Int Delta = 0;

Void form1_load (Object sender, eventargs e ){
Delta = clientrectangle. Width-textbox1.width;
}

Void form1_sizechanged (Object sender, eventargs e ){
Textbox1.width = clientrectangle. Width-delta;
}

During the form's Load Event, we capture
Delta between the width of the text box and the width of the Client
Rectangle so that when the form's size is changed, we can reset
Width of the text box to maintain the difference in width as
Constant. Keeping this difference constant means keeping the distance
Between the right edge of the text box a fixed number of pixels from
The right edge of the form. This is called Anchoring .
Default, all controls are anchored to the top and left edges of their
Containers (which may be a form or a control that contains other
Controls). We're already accustomed to the operating system moving our
Child controls to keep this anchoring in tact as the container's left
Or top edge changes. However, the operating system can only do so much.
It will not resize our controls to anchor them to other edges, which
Leads to resizing code or, more commonly, the fixed-sized form styles.
Fortunately, Windows Forms has direct support for anchoring, saving us
From writing this code at all.

You can change the edges that a control is anchored to by changingAnchorProperty to be any bitwise combination of the values in the anchorstyles enumeration:

 
Enum anchorstyles {
None,
Left, // default
Top, // default
Bottom,
Right,
}

Resizing the text box in our current example so that it's resized as the form is resized is a matter of changingAnchor
Property to include the right edge as well as the left and the top
Edges. Using the property browser, you even get a fancy drop-down
Editor, as shown in figure 4.

Figure 4. Setting the anchor property in the property Browser

Docking

as
powerful as scaling and anchoring are, they still won't do everything.
for example, if you wanted to build a text editor, you 'd probably like
to have a menu, a toolbar, and a status bar, along with a text box that
takes up the rest of the client area not occupied by the menu, the
toolbar, And the status bar. anchoring wocould be tricky in this case,
because some controls need more or less room depending on the runtime
environment in which they find themselves. instead of trying to anchor
to zero pixels away from the edges, it wowould be easier to simply tell
the form that the text box showould take whatever space remains in the
client area. for that, we have docking.

DockingIs a way
To specify a specific edge that we 'd like to have a control hug.
Example, Figure 5 shows a form with three controls, all docked.
Menu is docked to the top edge, the status bar is docked to the bottom
Edge, and the text box is docked to fill the rest.

Figure 5. A docking example

The docking behavior is achieved by setting each control'sDockProperty to one of the values in the dockstyle enumeration (exposed nicely in the property browser as shown in Figure 6 ):

 
Enum dockstyle {
None, // default
Left,
Top,
Right,
Bottom,
Fill,
}

Figure 6. Setting the dock property in the property Browser

Splitting

Often,
When docking is used, you 'd like the user to have the ability to resize
Some of the controls independently of the size of the form itself.
Example, the Windows File explorer splits the space between the toolbar
And the status bar with a tree view on the left and a list view on
Right. to resize these controls, the file explorer providesSplitter,
Which is a bar separating two controls that the user can drag to change
The proportion of Space shared between them. A simple example ofSplitterControl betweenTreeviewControl docking to the left edge andListviewControl docked to fill is shown in figure 7.

Figure 7. An example of splitting (notice the cursor indicating a potential drag)

SplitterControls are available in the toolbox. controls can be split vertically by settingDockProperty to dockstyle. Left (the default), or horizontally by settingDockProperty to dockstyle. Top. An example of horizontal splitting in shown in figure 8.

Figure 8. Horizontal splitting

Grouping

To
Achieve advanced layout effects, it's often necessary to break
Problem down into groups. For example, imagine a list of people on
Left and a list of details about the current selection on the right,
Shown in Figure 9.

Figure 9. grouping, docking and anchoring example

in
this example, there are concepts that you 've already seen. notice the
splitter in the middle, splitting the two group box controls. you can't
tell by looking at a single picture, but as the group boxes change
size, the controls inside the group boxes also change size. this is
accomplished because of two attributes of group boxes. the first is
that group boxes are container controls , that is they act as a
parent for child controls, just like a form does. the list box on the
left is a child of the group box on the left, not a child of the form
directly. likewise, the label and text box controls on the right are
Children of the group box on the right.

the second important
attribute of container controls is that they share the same layout
characteristics of forms in that child controls can be anchored or
docked. because of this, the anchoring and docking settings of a
Control aren't relative to the edges of the form, but rather to the
edges of the container; for example, the Group boxes in this case. so,
the list box in Figure 9 is actually set to dockstyle. fill to take up
the entire client area of the group box. likewise, the anchoring
Properties of the text boxes on the right are anchored top, left, and
right, so as the group box changes position relative to the parent form
or changes width, the text boxes act as you wowould have CT relative to
the group box.

TheGroupboxControl is one of three container controls Windows Forms provides; the other two beingPanelControl andTabcontrol.
The panel control is just like a group box doesn't that there is no
Label and no frame. A panel is handy if you 'd like something that looks
And acts likeSub-Form(A form within a form).TabcontrolIs a container or one or moreTabpageControls, each of which is a container control with a tab at the top, as shown in figure 10.

Figure 10. A tabcontrol with two tabpage controls

Custom Layout

The
Combination of anchoring, docking, splitting, and grouping solves
Large majority of common layout problems. However, it won't solve them
All. For example, automatically spreading controls proportionally
Using ss a client area in a table or grid-like manner, as shown in figure
11, can't be accomplished using these techniques.

Figure 11. custom layout example

For
Creating a layout as shown in Figure 11, it's best to use as much
You can from the provided bag of tricks and then to fall back onLayoutEvent on the form or the container controls to handle the rest. As an example, the followingLayoutEvent Handler arranges nine button controls proportionally as the form is resized:

Void gridform_layout (Object sender, layouteventargs e ){
// Arrange the buttons in a grid on the form
Button [] buttons = new button [] {button1, button2 ,...,};
Int Cx = clientrectangle. width/3;
Int Cy = clientrectangle. Height/3;
For (int row = 0; row! = 3; ++ row ){
For (INT Col = 0; Col! = 3; ++ col ){
Button button = buttons [col * 3 + row];
Button. setbounds (CX * Row, Cy * Col, CX, CY );
}
}
}
Where are we?

scaling lets us
arrange controls on a form at design time with one font setting, but
still have the form look right under another font setting. for example,
WE cocould have our controls at design time set to a normal font setting,
but still have the form look correct when using a large font setting.
anchoring lets us Resize and move controls that need to maintain a
fixed distance along some edges. docking lets us hand an entire edge
over to a control. splitting lets us resize docked controls. grouping
lets us break down our control layout into manageable pieces. and when
none of those things work, the layout event is the backdoor that lets us do what the existing arsenal can't do.

NoteThis material is excerpted from the forthcoming Addison-Wesley title:Windows Forms programming in C #
By Chris sells (0321116208). Please note the material presented here is
An initial draft of what will appear in the published book.

Chris sells
Is an independent consultant, specializing in distributed applications
In. NET and COM, as well as an example uctor for developmentor. He's
Written several books, includingATL Internals, Which is in the process of being updated for atl7. he's also working onEssential Windows FormsFor Addison-Wesley andMastering Visual Studio. NET
For O 'Reilly. In his free time, Chris hosts the Web Services devcon and
Directs the Genghis source-available project. More information about
Chris, and his varous projects, is available at http://www.sellsbrothers.com.

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.