The book of visual basic 2005 net insight for classic vb developers 2006 - phần 3 ppt

51 255 0
The book of visual basic 2005 net insight for classic vb developers 2006 - phần 3 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

VB 2005 Basics 85 Once you create a variable based on a delegate, you can assign a method to it by using the AddressOf operator. The AddressOf operator lets Visual Basic 2005 know that you are using a reference to a method, not trying to run it directly. Dim MyDelegate As ProcessFunction MyDelegate = AddressOf CapitalizeName Once you set a delegate, you can run the method later, just by using the delegate: ' Calls the CapitalizeName() function and assigns its return value ' to UCaseName. Dim UCaseName As String UCaseName = MyDelegate("samantha jones") This is a useful technique, because it allows what programmers call an extra layer of indirection. This means that the code you create is more generic and has a better chance of being reused. Here’s a function that accepts a delegate as an argument and uses the function specified by the delegate to perform a task: Public Sub ProcessArray(MyArray As String(), _ FunctionToUse As ProcessFunction) Dim i As Integer For i = 0 to MyArray.GetUpperBound(0) MyArray(i) = FunctionToUse(MyArray(i)) Next i End Sub You call the subroutine like this: Dim CustomerNames() As String = {"bob evans", "chan park", "jill svetlova"} ProcessArray(CustomerNames, AddressOf CapitalizeName) The result of this sleight of hand is that each element of CustomerNames will be modified according to the CapitalizeName() method. By using a delegate, you can create a single ProcessArray() subroutine that can process array elements in a variety of different ways, depending on the FunctionToUse reference that you supply. You only need to write the code in ProcessArray() once, but you still get ultimate flexibility (and the envy of your colleagues). NOTE It can become a little confusing to keep all of these ingredients in mind at once. To perform this delegate test successfully, you need to define the delegate, create a delegate variable, point the delegate variable at the right method, and then run the method through the delegate. You can see these steps in action by using the sample code avail- able online—check out the DelegateTest1 and DelegateTest2 projects. bvb_02.book Page 85 Thursday, March 30, 2006 12:39 PM 86 Chapter 3 Delegates won’t receive much more attention in this book, for two reasons. First, delegates can often be replaced by objects and methods. For example, we could rewrite the preceding ProcessArray() example to use a collection of special Customer objects that support a Process() method. (If the following example is a little perplexing, don’t worry; all will be explained in Chapters 5 and 6.) Public Sub ProcessArray(MyArray As Customer()) Dim MyCustomer As Customer For Each MyCustomer In MyArray MyCustomer.Process() Next End Sub A second use of delegates is to allow communication between different objects, by having one object store a delegate that contains a method in another object. However, there is also a better alternative for this type of communication—events, which are really just delegates with some added conveniences. You’ll learn how to work with events in detail in Chapter 5. What Comes Next? This chapter has provided a whirlwind tour through dozens of different language changes introduced when VB.NET replaced Visual Basic 6. The most fundamental concept presented here was the common class library, which is a complete programmer’s toolkit stocked with most of the features you could ever need in any language. This chapter also explained how and why many of the features that VB programmers have relied upon for years are now changing from stand-alone functions into class methods and are being grouped with the objects that they relate to. The key to understanding the new .NET world is realizing that every- thing is an object. The next step is to dive into object-oriented programming with the next few chapters. Additionally, you might want to start making forays into the class library reference to find out what methods and properties are exposed by the common data types. bvb_02.book Page 86 Thursday, March 30, 2006 12:39 PM 4 WINDOWS FORMS Windows forms are the building blocks of the traditional graphical programs designed for the Windows operating system. Most of the applications you use, from office produc- tivity software such as Microsoft Word to interactive games and multimedia products, can be considered Windows Forms applications. The hallmark of a Win- dows Forms program is that every part of its user interface is built out of windows. Windows Forms applications are all-purpose solutions to many pro- gramming problems. And .NET 2.0 makes it easier than ever to design a rich interface with support for resizing forms, splitting windows, and anchoring and docking controls. VB 2005 also takes the confusion out of Multiple Document Interface (MDI) applications, adds enhanced designers that let you build trees and lists by hand, and introduces the most powerful toolbars and menus yet. bvb_02.book Page 87 Thursday, March 30, 2006 12:39 PM 88 Chapter 4 Perhaps the most remarkable shift from classic VB is the fact that each form, along with all the controls on it, is now completely defined in Visual Basic code. This means that as you use the designer to rearrange your user interface and set control properties, the IDE actually quietly stores the infor- mation in a .vb code file. This allows you to tweak these settings by hand, or even to dynamically create a portion of the user interface while the applica- tion is running. All in all, it gives you greater control over your application. New in .NET .NET introduces a whole new model for working with forms—one that could easily occupy an entire book. It saves C++ developers the effort of wrestling with the MFC framework and gives Visual Basic programmers a level of con- trol they’ve never had before. A unified model for Windows applications All .NET languages share the same Windows Forms (or WinForms) tech- nology, which means that Microsoft won’t introduce new controls that are available only to developers using a certain language. Just as all .NET languages share a common runtime, they also all use exactly the same user interface toolkit. The component tray In earlier versions of Visual Basic, controls were such a popular and easy way to add functionality to a program that they were used even when the “control” (for instance, a timer) didn’t require a visual interface. In VB 2005, these invisible components are no longer placed on a form’s draw- ing area. Now they are organized in a dedicated component tray. Anchoring and docking These are the kind of little frills that win the hearts of developers. Anchoring and docking let you make controls move and change size automatically, so that you never need to write resizing code again. And if you have a more sophisticated layout in mind, you’ll get a great start with .NET’s intelligent panel controls. Forms are classes Visual Basic 6 forms had a dual identity, acting both as objects and as classes at the same time. In Visual Basic 2005, a form is just another class that inherits from System.Windows.Forms.Form. Even better, all of its charac- teristics—including such details as its position and the properties of the contained controls—are included automatically in the class code. MDI enhancements .NET removes many traditional restrictions on your ability to work with windows, and nowhere is that more apparent than with MDI windows. Not only can you turn any form into an MDI parent by setting a simple property, but you can also turn any other Windows form into a child at runtime with a single command. bvb_02.book Page 88 Thursday, March 30, 2006 12:39 PM Windows Forms 89 Extender providers In a bid for even greater organization, Visual Basic 2005 introduces the concept of providers, which are controls that enhance other controls on the same form with additional properties. For example, if you want your controls to have tooltips, you can add a ToolTip control to the component tray, and voilà!—every control has a new ToolTip property. Getting Started Windows Forms applications get their name from the fact that they are built out of a number of windows, or forms. Different applications use windows differently. For example, multiple document (MDI) applications, such as Visual Studio, can designate that several windows be manipulated inside a larger “container” window. Other applications—Windows Explorer, for example—use a single window that divides itself into several resizable panes. Each of these types of interfaces is easy to create with Visual Basic 2005. At this point, it’s a good idea to start a Windows Forms project and try adding some controls to it. Much as in earlier VB versions, you add a control by selecting the icon and drawing it on the design surface. You can also add more forms by right-clicking your project in the Solution Explorer and choos- ing Add Add Windows Form. NOTE In this section, we explore how you can design the interface for a project with a single form. As you start adding more forms and writing code to handle events and to com- municate information from one form to another, the VB 2005 world takes a couple of twists. We’ll explore the implications of multiple forms, and their underlying architec- ture, later in the chapter. The new Windows Forms engine works like the traditional Visual Basic 6 Form Designer when it comes to creating and designing forms. Properties are still configured in a Properties window. Controls can be moved, copied, and aligned with the grid, exactly as they could be in classic VB. But you’ll notice that the Toolbox packs in a great deal more—it’s now divided into several subgroups, each with its own collection of related controls. You’ll find the familiar Windows standards in the Common Controls group. The Component Tray In classic VB, some features would be implemented through “invisible” controls, the most common example being the Timer control. This was a convenient way to add functionality, but it was a little messy—after all, controls were designed to provide user interface, not to replace .dll files and other code components. Visual Basic 2005 provides a cleaner imple- mentation through a tool called the component tray. You’ll notice this new addition as soon as you try to draw an “invisible” control on the design surface. (For example, try one of the items in the Components section of the Toolbox.) Instead of appearing on the form, bvb_02.book Page 89 Thursday, March 30, 2006 12:39 PM 90 Chapter 4 where they might be obscured by other, legitimate controls, the invisible components will now appear in a special area of the window, as shown in Figure 4-1. This lets you easily add support for menus, timers, and standard Win- dows dialog boxes (such as Open, Save, and Print, and selection windows for Font, Color, and Print Settings). You could create these controls directly using a couple of lines of code that access classes in the System.Windows.Forms name- space, but the component tray makes the process effortless. Figure 4-1: A timer in the component tray Custom Designers Some controls have complex properties that can’t be specified by simply entering strings in the Properties window. A typical example is the TreeView control, which contains a hierarchy of different elements (called nodes). In the past, the content for complex controls like the TreeView couldn’t be created at design time—instead, you needed to generate it programmatically. How- ever, .NET outfits many of its most impressive controls with custom designers that solve this problem. For example, a ListBox control can be filled at design time using the handy ListBox designer. Just find the Items property in the Properties window, and click the ellipsis (. . .) next to the word Collection. A designer window will appear where you can enter your list items (see Figure 4-2). A similar tool is available for the Items property in the ListView control and for the Nodes property in the TreeView control. These custom designers are lightweight and straightforward. bvb_02.book Page 90 Thursday, March 30, 2006 12:39 PM Windows Forms 91 Figure 4-2: Configuring list items with the designer The best way to get used to this new system is to try it out. The basic principle is that you start by adding items (for example, individual nodes and buttons) to the list on the left. Then, to configure the properties for an individual item, you select the item from the list and modify the property list that appears on the right. And remember, if you want to add an image to an item, you’ll need an associated ImageList control, which will provide a collection of pictures to choose from. Thankfully, the ImageList control also has its own designer, so inserting and rearranging graphics files is a breeze. Locking Your Controls It used to be that getting controls to line up perfectly in a complex interface could be a slow and tricky process. It sometimes involved turning off the Snap to Grid feature in order to position some of the controls exactly, and then re-enabling it so that other controls could easily be placed in positions that lined up consistently. And once you finally had your controls perfectly arranged, you risked scattering them with an accidental mouse click. Locking is a convenient design-time feature that can help you prevent this type of accident. It existed in Visual Basic 6, but only in a crude “all or nothing” form. As soon as you locked a VB 6 form, you couldn’t change anything until you unlocked it, which often didn’t allow enough flexibility. The locking feature still exists in Visual Basic 2005—just right-click your form and select Lock Controls (and do it again to unlock them). However, VB 2005 also provides a more useful version of this feature that allows you to lock individual controls. To use it, select the control and change its Locked property to True. You can then add new controls and rearrange exist- ing ones, without having to worry that you’ll accidentally move the locked control that you’ve positioned perfectly. bvb_02.book Page 91 Thursday, March 30, 2006 12:39 PM 92 Chapter 4 Control Layout As any Windows developer knows, it’s easy to add controls to a form, but it’s much harder to arrange those controls in a perfectly pleasing layout. The task becomes even trickier when you need to take into account different window sizes and screen resolutions. Fortunately, .NET offers a set of features that allow you to build flexible layouts that adapt easily to different conditions. In the following sections, you’ll tour the highlights. Anchoring Anchoring is a simple idea that saves a lot of trouble. The best way to under- stand anchoring is to see it in action. Examine the window shown in Figure 4-3. Figure 4-3: An ordinary window By default, Windows controls are “anchored” to the upper-left corner of a form. This used to mean that as a form was resized, the controls stayed put, because the position of the upper-left corner does not change. As a result, unless you wrote explicit resizing code, the embarrassing blank borders at the bottom and right edges of your form would grow wider, as shown in Figure 4-4. Figure 4-4: An embarrassment bvb_02.book Page 92 Thursday, March 30, 2006 12:39 PM Windows Forms 93 If, on the other hand, a control could be anchored to the bottom of the form, its position would drop as you lengthened the form, guaranteeing that the distance between the control and the bottom edge of your form always remained constant. This anchoring to any side of a form is exactly the ability that .NET forms provide. To change a control’s anchoring, find its Anchor property in the Properties window, and then change it using the special drop-down control (see Fig- ure 4-5). Click to select the edge or edges that your control should bind to. For example, you might want to anchor a control to the lower-right corner, thus ensuring that the control will always be a fixed distance away from the bottom and right edges of your form. Figure 4-5: Anchoring options You can even anchor a control to more than one side. In this case, the control has to grow automatically to maintain a consistent distance away from the form edges as the form is resized. In our sample resizable form shown in Figure 4-6, the command buttons are anchored to the bottom right, the group box is anchored to the left, right, and top (so it will grow to fit the form width), and the radio buttons are anchored to the top left (the default). A check box allows you to test anchoring by turning it on and off. (You can try this example with the Anchoring project that’s included with the sample code for this chapter.) Figure 4-6: A basic resizable form bvb_02.book Page 93 Thursday, March 30, 2006 12:39 PM 94 Chapter 4 There are some controls that you’ll never want to be resized. For example, buttons should always be a standard, consistent size—they look bizarre if they start to grow as a form changes size. This is one of the main problems with many of the commercial add-ins for automatic resizing that were in vogue before .NET hit the scene. A sophisticated program will resize the areas of its interface that can ben- efit from more screen real estate. For example, if you are creating a window with a group of check-box settings, you should probably give it a fixed border, because the window will not need to change size. On the other hand, if you have a window that contains a control with a lot of scrollable information (a RichTextBox, a ListView, or a DataGridView, for example), you should allow it to grow when resized, by docking it to opposite sides. NOTE Anchoring is always relative to the container that holds the control. For example, if you put a button inside a panel, you can use anchoring in two ways. You can anchor the panel so it moves or changes size when the form is enlarged, and you can anchor the button so it moves or changes size as the panel is resized. Docking Docking allows a control to latch onto an edge of a window and resize itself automatically. To add docking to a control, find the Docking property in the Properties window, and choose an edge on which to dock (Figure 4-7). You can only dock against a single edge (or choose to fill the entire form), and you can’t dock and anchor a single control. Figure 4-7: Docking options The first time you use docking, you’re likely to become slightly frustrated. While docking does what it claims, it also forces the control to sit flush against the docked edge and take its full width. This often means that your control is squeezed up against the side of the form, without enough of a border, as shown in Figure 4-8. bvb_02.book Page 94 Thursday, March 30, 2006 12:39 PM [...]... require time-consuming manual repositioning or resizing Visual Basic 2005 handles this kind of situation quite a bit differently Visual Basic 2005 Forms “Under the Hood” Every Visual Basic 2005 file has the extension vb, whether it is a form, a class, or a module However, when you create a form VB 2005 actually creates two files These two files are definitions for the same form class, but there’s a clear... However, there’s more here that meets the eye To see the other side of the story, choose Project Show All Files from the menu Now you’ll find that every form is paired with a designer file For example, Form1 .vb has Form1.Designer .vb (Visual Studio generates this name automatically by adding Designer on the end of your form name.) Figure 4-2 3 shows the designer file for Form1 Figure 4-2 3: The designer... the end of this file is all of the Visual Basic event handler code that you created (in the preceding example, it’s just the Click event handler for the cmdQuit button) But before that is a great deal of information that sets the properties and position of all the interface elements in your program 112 C h ap te r 4 bvb_02 .book Page 1 13 Thursday, March 30 , 2006 12 :39 PM This code resembles Visual Basic. .. ordinary form named Form1 .vb (An initial, blank form named Form1 .vb is added to all new Windows application projects.) If you look at the code for this form (choose View Code from the menu), you’ll see an empty class definition that’s just waiting to receive your code: Public Class Form1 End Class Wi nd ows F or ms 1 13 bvb_02 .book Page 114 Thursday, March 30 , 2006 12 :39 PM Figure 4-2 2: A basic VB 2005 form... 100 C h ap te r 4 bvb_02 .book Page 101 Thursday, March 30 , 2006 12 :39 PM Next, choose the desired event from the list on the right side (see Figure 4-1 5) Figure 4-1 5: Choosing an event NOTE Of course, dedicated VB developers know there’s a shortcut for most controls Doubleclick the control on the design surface, and Visual Studio will create an event handler for the default event (the event that’s most... additional information, and so it sends an empty e object Wi nd ows F or ms 101 bvb_02 .book Page 102 Thursday, March 30 , 2006 12 :39 PM On the other hand, the MouseMove event does include important extra information: the current coordinates of the mouse pointer In the following example (see Figure 4-1 6), the event handler retrieves and displays this information Figure 4-1 6: Tracking the mouse Here’s the code... docking For example, you could anchor the TreeView to all sides or set the Dock property to Fill so that the TreeView automatically resizes itself to occupy the W in dow s For m s 97 bvb_02 .book Page 98 Thursday, March 30 , 2006 12 :39 PM entire panel That way, the user can move the splitter bar at runtime to change the size of the PictureBox and the TreeView controls Figure 4-1 2 shows the result of resizing... sort of a strange hybrid For example, controls are defined with a statement like Begin VB. Label lblHello, which follows the C style of syntax by indicating the type of element to be created (VB. Label), followed by the name of the item (lblHello) Though this code is clearly present and accessible, it wasn’t shown anywhere inside the Visual Basic 6 IDE Figure 4-2 1: A basic VB 6 form The “code” in a VB. .. Thursday, March 30 , 2006 12 :39 PM Visual Basic 6 Forms “Under the Hood” In Visual Basic 6, every form is stored in a file with the extension frm, and any binary information (pictures, for example) is stored in a corresponding file with a frx extension If you open a VB6 frm file in a text editor, you’ll see information like this: Begin VB. Form frmHello Caption = "Hello World Program" ClientHeight = 31 95 ClientLeft... that a form could have only one Default and one Cancel button Wi nd ows F or ms 1 03 bvb_02 .book Page 104 Thursday, March 30 , 2006 12 :39 PM Exploring NET Forms So far, you’ve learned how to combine controls to build a snazzy form and how to write the code that drives them The next step is to assemble a suitable group of forms into a complete multiwindow application As in Visual Basic 6, every NET form . surface. (For example, try one of the items in the Components section of the Toolbox.) Instead of appearing on the form, bvb_02 .book Page 89 Thursday, March 30 , 2006 12 :39 PM 90 Chapter 4 where they. Figure 4-4 . Figure 4-4 : An embarrassment bvb_02 .book Page 92 Thursday, March 30 , 2006 12 :39 PM Windows Forms 93 If, on the other hand, a control could be anchored to the bottom of the form, its. information from one form to another, the VB 2005 world takes a couple of twists. We’ll explore the implications of multiple forms, and their underlying architec- ture, later in the chapter. The

Ngày đăng: 13/08/2014, 08:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan