Chapter 2 user interface construction

Source: Internet
Author: User
Tags configuration settings microsoft outlook
ArticleDirectory
    • New Concept
    • Toolstrip Control
    • Flowlayoutpanel and tablelayoutpanel controls
    • Webbrowser Control
    • Activedocumenthost Control
    • Drill
    • Create an office Interface
    • Interaction with Web Content
    • Interaction with document content
    • Summary
    • New Concept
    • Margin and padding
    • Automatic completion
    • Configuration
    • Drill
    • Use padding
    • Automatic use
    • Use the new configuration system
    • Summary

Content of this chapter:

This chapter explores the controls provided by Microsoft. NET Framework 2.0 and their improvements to existing controls. These features allow you to create applications with professional appearancesProgramTo provide a better end user experience and reduce coding workload.

Content on this page
Application: new Windows Forms Control
Application: changes to existing Windows Forms controls

Application: new Windows Forms Control

This application introduces many new controls in Microsoft Visual Studio 2005, allowing them to create great Windows Forms user interfaces.

New Concept

Visual Studio has provided a huge pre-built control library for many years, allowing developers to quickly create a user interface for Microsoft Windows applications. However, the features and visual styles of these components often lead to a significant difference in the appearance of the application compared to other Microsoft products (such as Microsoft Office and Internet Explorer. Visual Studio 2005 introduces many new controls to solve this problem. These controls provide the same advanced appearance and custom support as Microsoft Office, allowing you to provide users with a familiar experience and more personalized options.

Toolstrip Control

Today's professional applications provide many features that allow users to completely customize their menu and toolbar positions, formats, and content. The user expects to execute tasks such as moving the toolbar, selecting the button to display, and controlling how much information is displayed in each item. In addition, they expect these controls to be neatly and uniformly displayed in applications. Toolstrip is a new Toolbar Control that supports all of these features and provides basic functions for the menustrip and statusstrip controls. You are no longer limited to adding buttons only to the toolbar. Toolstrip allows you to add seven different types of items, such as toolstripbutton, toolstripcombobox, toolstriptextbox, and toolstripsplitbutton.

When you add toolstrip to a form, note that it is like an office toolbar by default. Many controls support a new pluggable rendering framework, allowing you to select the display mode of the control. Currently, toolstrip has two main "appearances". You can use the rendermode attribute to select the desired appearance. The system providesSystemValue, indicating that you want the control to follow the current Windows display settings. In addition,ProfessionalValue, indicating that you want the control to look similar to the corresponding control in Microsoft Office.

Toolstrip supports many new types of behaviors, including floating, merging, and item overflow. Floating is an action that allows you to drag and drop a toolbar to different positions of the form and automatically align the toolbar with the position. When toolstrip is added to the form, multiple raftcontainer controls are automatically added to the integrated development environment (IDE) to support floating. You can setRaftAttribute to specify the initial position of the toolstrip. During running, you can move the toolstrip to any other raftcontainers.

Merging combines items in two toolstrip into one toolstrip. You can use the allowmerge attribute to specify whether a specific toolbar can be merged. Then, you can use the mergeaction and mergeindex attributes to manage the merging behavior of each item.

Item re-sorting is a behavior that allows users to rearrange toolbar and menu items. You can set the allowitemreorder attributeTrueTo enable item re-sorting. During running, you can drag and drop an item while holding down the Alt key to move the item.

Flowlayoutpanel and tablelayoutpanel controls

Visual Studio 2005 provides two new layout controls to help you locate common controls. RegularPanelControls use absolute positions to determine the positions of their child controls. Flowlayoutpanel positions each control relative to the control added to the panel just before it. By default, the control is arranged from left to right, from top to bottom, but you can control the direction by using the flowdirection attribute. When the content or panel size of a child control changes, you want the control to be automatically relocated. flowlayoutpanel is very useful.

Tablelayoutpanel is a panel that contains a non-table structure that allows you to place a control in each table cell. You can specify the number of rows and columns in an internal table, as well as the size rules for each row and column. Tablelayoutpanel is useful when you need to define the main and fixed size parts of a form. You can also use it to quickly create a data input interface in table format. But remember, you can only add one control to each cell. Therefore, if you want a cell to contain multiple child controls, you must first addPanelAnd then add the two child controls toPanel.

Webbrowser Control

Currently, Visual Studio 2005 provides optimized hosting packages for ActiveX Web browser controls. This control provides access to the full DHTML rendering function of Internet Explorer. You can use this control to add multiple web browsing functions to an application. For example, you can read HTML document files from an application. Or allow users to link to content on the Internet. The webbrowser control is very simple to use. It provides some powerful options to support deep integration between DHTML and winform resources.

You can callNavigateMethod and provide the resource URL to download and display a document. Once the load is complete, you can useDocumentThe property is programmed to access the DHTML Dom. This attribute allows you to directly read and modify the structure of a document. You can use some methods (such as goforward, Gohome, gosearch, and Goback) to perform standard navigation tasks. You can evenCodePublish a hosted object to allow scripts on the page to call hosted applications. What we need to do is to provide an object to the objectforscripting attribute. By processing webbrowser events (suchNavigating,Navigated, Progresschanged, and documentcompleted) to monitor the download progress.

Activedocumenthost Control

ActivedocumenthostControls are a bridge between Windows Forms applications and Ole resources. You can call the loadfrom method and provide the resource path to load and display resources. Activedocumenthost starts an application instance registered for this specific type of resource. For example, if you load a Microsoft Word document, activedocumenthost automatically starts Microsoft Word and displays the document in read-only status. By default, double-click the control to switch to editable mode, and display the toolbar and menu of the editing application. You can use some attributes (such as showmenus and showtoolbars) to control most of the displayed content.

Drill

This walkthrough demonstrates how to use these new controls to create a Windows Forms interface with a more professional appearance and ease of use.

Create an office Interface

The documentbrowser form displays an interface that draws many design elements from various Microsoft products, including office and Internet Explorer. Note that two toolstrip are displayed as the Office toolbar, which has a vertical gradient background and has a "handle" on the left edge ". One toolstrip contains a text box. There is also the third toolstrip control, which is located at the bottom left of the form and has two items: documents and web pages. By setting its layoutstyle to vertical, you can change toolstrip to a style similar to Microsoft Outlook. The status bar below the form is a statusstrip control, which has two child controls: statusstrippanel and toolstripprogressbar. By setting its style attribute to continuous, you can configure the progress bar to display the progress in a continuous manner.

When running the application, click the toolbar and drag it to any edge of the form. You can see that they are automatically docked on this side. This operation is possible because each edge of the form has a raftingcontainer control. When toolstrip is added to a form, Visual Studio automatically adds these containers. You can also sort these items again, or even move the item from one toolstrip to another by holding down the Alt key while dragging it.

Interaction with Web Content

The application uses the webbrowser control to load and display web content. At runtime, click "Web pages" in the lower left corner of the form. Enter a URL in the address text box of the toolbar. Click Go to locate the document.

NoteIf you cannot access the Internet, you can use an HTML page named "msdn home page.htm" in the application directory.

When loading an application, note that the progress bar and status text below the form are updated. When the document is loaded, an entry is displayed in the History List on the left side of the browser pane. This progress can be monitored by processing multiple webbrowser events. This process starts with the btngo_click event handler. In this processNavigateThe method tells webbrowser to load a document:

 
Wbrbrowser. navigate (txtaddress. Text)

When webbrowser starts to locate this resourceNavigatingEvent. The wbrbrowser_navigating event handler retrieves this URL from the event parameters and returns the URL to statusstrip.PanelSend a message to indicate that the download is in progress:

 
Setstatus ("navigating to '" + E. url + "'")

When the webbrowser loads a document, it periodically triggers the progresschanged event. The wbrbrowser_progresschanged event handler first updates the progress bar in statusstrip. If it is displayed as 100%, It is reset and then incremented with a value of 5%:

 
If pbrprogress. value> = pbrprogress. Maximum then clearprogress () end if pbrprogress. increment (5)

Webbrowser triggers the documentcompleted event after the document is loaded. You can use this event to notify users that the content is available or to record the download results. The wbrbrowser_documentcompleted event handler retrieves the document title from the document URL of the event parameter. This information is used to fill in a new listviewitem and add it to the History List View. The status text and progress bar are reset at the end of the process.

 
Dim title as string = E. URL dim visited as string = datetime. now. tostring () dim docinfo as new listviewitem (new string (1) {Title, visited}) lvwhistory. items. add (docinfo) setstatus (string. empty) clearprogress ()
Interaction with document content

The application also allows you to load and display files registered as permitted Ole hosts. Office documents, sound files, and. Avi image files are examples of "active" data. First, you can select the documents button at the bottom left of the form to load a file. Then, enter the local path of the desired file in the address text box and click "go. This document is displayed in activedocumenthost. If the document can be edited, double-click activedocumenthost to start the document in the associated host application. The menu and toolbar of the Host application are displayed in the documentbrowser form.

Compared with the webbrowser control, activedocumenthost has fewer progress-related events. However, when it loads and displays the document, it triggersLoadedEvent. The ahddocument_loaded event handler first retrieves information about the loaded document. Then, it creates a listviewitem and adds it to the History List View:

Dim URL as string = adhdocument. sourcedocument dim visited as string = datetime. now. tostring () dim docinfo as new listviewitem (new string (1) {URL, visited}) lvwhistory. items. add (docinfo) setstatus (string. empty) clearprogress ()
Summary

. NET Framework2.0 the new Windows Forms control allows you to create more professional and powerful applications without relying on third-party components. Toolstrip provides a powerful mechanism for you to create menus, tools, and status bars, so that their appearance and behavior are similar to those in other applications that you are familiar. This allows users to accept and improve user satisfaction more quickly and directly. Webbrowser and activedocumenthost allow you to integrate external data into applications. Webbrowser is designed to implement reliable and common download and rendering of DHTML content, while activedocumenthost provides a mechanism for carrying and editing Ole data types.

Back to Top

Application: changes to existing Windows Forms controls

This application studies some changes and new features to the Windows Forms framework, which affect many existing and new Windows Forms controls.

New Concept

. NET Framework 2.0 and Visual Studio 2005 introduce many new Windows Forms development features that have a wide impact on how to use Windows Forms controls at design time and runtime. These functions affect many behaviors, including the layout and positioning of controls, runtime data input, and application configuration and personalization.

Margin and padding

Ensure that controls are located and placed in a consistent manner, which is important for creating applications that are easy to understand and navigate. Unfortunately, the process of locating controls is time-consuming and laborious. The correct positioning is to ensure that the spacing between controls is consistent. For example, you may have a series of buttons below the form, and each button requires a precise spacing of 10 pixels. This usually involves placing a button, recording its left attribute, and then changing the left attribute of the next button to the desired value. In another example, when you have a container control, you want to ensure that the distance between its sub-control and the edge of the container cannot be less than 8 pixels. This setting requires at least placing the first control as the positioning point, and then alignment other controls accordingly.

. NET Framework 2.0 introduces two new concepts about controls-margin and padding, greatly simplifying the work involved in the above situation.MarginIs the external spacing between two controls, whilePaddingIs the internal spacing between the edge of a control and its content. Therefore, the distance between the right edge of a button and the left edge of another button is the margin between them. On the other hand, the spacing between the edge of the Panel and its child controls is the padding of the Panel.ControlThe class now hasPaddingAndMarginTherefore, a widget can declare and forcibly specify its spacing requirements.

Visual Studio IDE is designedMarginAndPaddingProperties to provide indicators of margin and padding, and according to theirMarginAndPaddingProperty auto-alignment control. Both attributes arePaddingType, which is a simple structure that allows you to provide unique values for each edge of the control: top, bottom, left, and right. Therefore, if you havePanel, Its padding. Left is set to 5, and you canPanelA child control is placed on the left side of the Child control andPanelWhen the left distance is 5 pixels, IDE automatically provides feedback. This allows you to quickly and accurately place controls in the appropriate location without manually setting their location attributes. These attributes are still valid when you adjust the widget size or reposition the widget at runtime.

Automatic completion

If you have used Internet Explorer, you will see the operation process automatically completed. Automatic completion refers to the following behavior: When you input data to a text control, the system automatically recommends the content that you may enter. This function is usually most useful when users need to input long or complex strings. To enable automatic solution completion to take effect, a prerequisite is that some datasets exist, which can be used by the system to find possible matching items.

Now, you can easily add automatic support to the text box and combo box of the Windows Forms Application. Both controls have three new attributes: autocompletemode, autocompletesource, and autocompletecustomsource. You can set autocompletemodeAppend,SuggestOr suggestappend to enable automatic completion. Set autocompletemodeAppendAutomatically append the most likely matching item to the current data. If it is setSuggestWill generate a drop-down list consisting of one or more recommended strings. Suggestappend simultaneously executes these two tasks. This control also requires a source list, which allows users to search for suggestions when entering data. The autocompletesource attribute allows you to select from some system sources, such as filesystem, historylist, recentlyusedlist, allurl, and customsource.

If customsource is selected, a string list must be provided to the autocompletecustomsource attribute. This can be completed at design or runtime. Custom sources are very powerful because they allow you to automatically complete behaviors for business data. For example, when the form is loaded and a category name list is provided to serve as the display source of the combo box and the automatic completion source, you can query the list of product categories from the database. This method allows you to quickly select a category without entering a full category name or manually navigation a long list of items.

Configuration

. NET Framework 1.1 provides a basic application configuration mechanism that allows you to define read-only application settings in the application configuration file. You can access these settings through the system. configuration. deleettings class, which uses keys to retrieve the settings and returns a weak type object that must be converted to the appropriate type. This mechanism is very useful in simple cases, which focus on relatively static data that can only be modified by the Administrator. However, many other application configurations require a more powerful and flexible solution .. Net Framework 2.0 and Visual Studio 2005 provide a new configuration system for Windows Forms applications. The system solves the limitations of previous solutions and introduces many new concepts, allowing you to experience a more complete and effective design experience and a more personalized end user experience.

NoteThe content provided here will appear in the market release (RTM) version. When writing this book, this configuration system is only partially implemented.

ImportantFrom now on, "Configuration System" refers to the new configuration system provided by. NET Framework 2.0 and Visual Studio 2005.

Configuration settings the Configuration System provides more powerful support for the definition, reading, and writing of configuration settings. Each setting is defined by its name, data type, scope, default value, and accessibility. All settings are strongly typed, And you can specify any serializable type. The configuration system supports many persistent value setting mechanisms, including string representation, XML serialization, and binary serialization.

You can also define the setting as one of the following two scopes: user or application. The application settings are read-only and the value is shared by all users of the application on the computer. By default, these values are stored in the application configuration file. User settings are stored and managed for each user and stored in the user. config file. You can set the user to read/write or read-only. One of the main functions set by the user is to configure the system's support for roaming windows configuration files. If the specified user settings should be roaming with the user's windows configuration file, these settings will automatically follow when they run the application from another computer. The following is an example of configuration settings:

<Usersettings> <windowsapplication1.mysettings> <setting name = "defaultview" serializeas = "string"> <value> allemployees </value> </setting> <setting name = "credentials" serializeas = "system. net. networkcredentials "> <value> some binary representation... </Value> </setting> </windowsapplication1.mysettings> </usersettings> <applicationsettings> <windowsapplication1.mysettings> <setting name = "employee_cs" serializeas = "string"> <value> Server = localhost; initial catalog = northwind </value> </setting> </windowsapplication1.mysettings> </applicationsettings>

The packaging configuration system requires you to use the packaging class to access the settings stored in the configuration storage. These packaging classes provide a strong interface to the configuration system and provide a complete description of the metadata of each setting. This allows the user of the packaging class to understand the configuration method of each setting without directly accessing the configuration file.

NoteYou should understand that the configuration system uses a pluggable architecture to connect and set up storage. Initially, the system only supports the storage settings in the configuration file, but at last it supports many potential storage settings.

The following is the packaging class shown previously:

Imports system. configuration imports system. net public class settingswrapper inherits system. configuration. applicationsettingsbase <applicationscopedsettingattribute (), _ defaultsettingvalueattribute ("Server = Local; initial catalog = northwind")> _ Public overridable readonly property employee_cs () as string get return ctype (Me ("employee_cs"), string) end get end property <userscopedsettingattribute (), _ defaultsettingvalueattribute ("allemployees")> _ Public overridable property defaultview () as string get return ctype (Me ("defaultview"), string) end get set me ("defaultview") = value end set end property <userscopedsettingattribute ()> _ Public overridable property credentials () as networkcredential get return ctype (Me ("credentials"), networkcredential) end get set me ("credentials") = value end set end property end class

Use the packaging class in the application code to access and modify configuration settings. For example, the following code is used to retrieveCredentialsNetworkcredential in user settings.

Dim wrapper as new settingswrapper () dim cred as networkcredential = wrapper. Credentials

Although the IDE supports manual creation of configuration files and packaging classes, Visual Studio 2005 provides full ide support for both tasks. In Visual Basic. net, you can right-click a project in Solution Explorer and select Properties to access the settings designer. On the property page, select Settings ". You will see a designer that allows you to define all aspects of the application and user settings. When you save the changes in the designer, Visual Basic automatically creates and fills in the corresponding configuration file. It will also create a packaging class and use my object to make the packaging class accessible as my. settings.

Visual Studio also fully integrates the settings into the Windows Forms design experience to provide a convenient mechanism for binding control properties to applications and user settings. This design experience is similar to the current data binding design experience. The "properties" window contains a new section named applicationsettings. When this attribute is selected, a dialog box is displayed, allowing you to bind various control attributes to configuration settings. Because the settings are strongly typed, IDE can even filter the list of available settings to display only the settings that are consistent with the selected Attribute type. The code generated by this process can fill in the properties of the control with the set value. However, when this property is changed or the application ends, no code is added to update these settings.

Currently, You need to manually set the persistence of any changed values stored. This task is not difficult, but it may take a lot of time if you consider that there are many control properties pointing to the configuration settings. To reduce this burden, some controls provide built-in support for automatic loading and persistence of their property values. This support is mainly used for layout and format-oriented settings, such as container controls (suchFormAnd splitcontainer)LocationAndSize. Other controls (such as toolstrip) may support other attributes, such as the order of each item and its current floating position. Controls that support automatic persistence configuration have two new attributes: savesettings and settingskey.

Drill

This walkthrough demonstrates how to use padding, Automatic completion, and a new configuration system to create a more powerful user interface.

Use padding

This application is designed to study how to copy the appearance of a Microsoft Office application. For example, Microsoft Outlook organizes functional areas of the interface into panels separated by removable splitters. Each visualization panel has a dark blue border with a single pixel and has a consistent spacing between the perimeter of the panel and between the panels. You can use a combination of multiple controls to achieve this appearance. This application only studies one of them.

Splitcontainer is the main container control. It displays the history list and buttons on the left side, and web content and document content on the right side. Splitcontainer consists of twoPanelThese two panels are composed of oneSplitterSeparated. AlthoughPanelThe widget does not allow you to directly specify the border color, but it can still easily implement the appearance described above. First, SetPanelThe borderstyle attribute of the control is set to none. Next, set the backcolor attribute to the border color you need. Finally, set the padding. All attribute to define the Border width. NowPanelPlace a control on andDockWhen the property is set to fillPanelA colored border is provided around the control.

Automatic use

When you type the resource URL in the address text box of the toolbar, the text box will be prompted with the automatic completion function. If you select this text box, you will see that its autocompletemode attribute is set to suggest. This setting is consistent with the automatic completion of Internet Explorer. The autocompletesource attribute varies according to the resource type you search. When you click the "events" or "Web pages" button in the lower-left corner of the form, the doctypebutton_click event handler runs. This event handler executes some basic status maintenance tasks on the interface. One task is to change the autocompletesource of the text box. If you click the "Web pages" button, autocompletesource is set to provide suggestions from all resolvable URLs. If you click the "documents" button, set autocompletesource to only use the file system:

 
Txtaddress. autocompletesource = autocompletesource. allurl... txtaddress. autocompletesource = autocompletesource. filesystem

You can test this behavior by running an application, click the "Web pages" button, and enter a URL starting with http. You should see a suggestion list automatically displayed in the drop-down list below the text box. If you enter a file path starting with a drive letter (such as C: //), no suggestions are given. Then, click the "documents" button and enter a URL starting with http: // again. You will not get any suggestions this time, because autocompletesource only uses the file system.

Use the new configuration system

When writing this book, the new configuration system does not have all the functions in Visual Studio. NET. However, you should still understand the available functions and how these functions are implemented. The application uses the Configuration System to provide users with personalized services by automatically saving some interface states when the form is closed. When the application starts, the information is reloaded so that you can see the same interface as the last time you left. In particular, the application stores the location of the splitter in the splitpanel and the windowstate of the form between user sessions. In addition, the application allows you to enable or disable this function in an option dialog box.

You can view the configuration by going to project properties and selecting the "Settings" tab. Three settings are defined: windowsstartupstate, rememberformstate, and splitterdistance. These settings are of the formwindowstate, Boolean, and int32 types. The default value is also specified. Note that although these three settings are all user settings, they can be easily defined as application settings. To view the location where the configuration file and packaging class reside, Click Show All files in Solution Explorer to expand my application. Under my application, mysettings. settings and mysettings. VB are displayed. Mysettings. settings is an xml configuration file containing the settings definition. Mysettings. VB is the packaging class that accesses these settings.

If you set rememberformstate to true, the application uses windowsstartupstate and splitterdistance to set it at startup. This decision occurs in the documentbrowserform_load event handler. The application also writes these attribute values back to the configuration settings when it is disabled. The documentbrowserform_formclosing event handler first checks the Boolean settings to determine whether the user wants to make persistent interface changes. If yes, the event handler simply reads data from the relevant properties and assigns them to the corresponding configuration settings. Once all the settings are complete, you can call the encapsulatedSaveMethod to send the changes to the configuration file:

If my. settings. rememberformstate then my. settings. windowstartupstate = me. windowstate my. settings. splitterdistance = splitcontainer1.splitterdistance my. settings. Save () end if

You can change the rememberformstate settings by selecting the tools | Options menu command in the main form. Optionsform is enabled. optionsform provides a check box through which you can modify the value of rememberformstate.

Summary

Margin and padding, Automatic completion, and new configuration systems reflect major advances in the Windows Forms technology, which will be available when the next version of. NET Framework and Visual Studio is released. These features have a wide impact on the Windows Forms experience of developers and end users. Enhanced functions (such as margin and padding) for developers' work efficiency allow you to perform more efficient and consistent interface layout. Enhanced functions (such as automatic completion) of end user productivity allow users to complete tasks faster and more accurately. Finally, the Improved Configuration System provides new levels of flexibility, management, customization, and personalization for all Windows Forms applications.

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.