Programming Visual Basic 2008 phần 3 docx

79 171 0
Programming Visual Basic 2008 phần 3 docx

Đ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

Project | 137 Although not actually parts of an assembly, this chapter also discussed the My namespace and directives, two Visual Basic features that impact what gets included in your assembly. Project This chapter’s project officially kicks off the coding of the Library Project (muted applause). We’ll start off with something simple: building the About form that pro- vides basic information about the application, including its version number. PROJECT ACCESS Load the Chapter 5 (Before) Code project, either through the New Project tem- plates or by accessing the project directly from the installation directory. To see the code in its final form, load Chapter 5 (After) Code instead. Our goal is a pleasant form that conveys basic information about the program, a form that looks something like Figure 5-4. Like any Visual Basic application for Windows, the creation of this form involves two steps: (1) adding controls to the form; and (2) writing the related code. Figure 5-4. Everything you wanted to know about the program 138 | Chapter 5: .NET Assemblies Adding Controls If there is one area where Visual Basic excels, it is form creation. Programs can be created by the simple dragging and dropping of prebuilt controls onto the surface of a prebuilt form. It’s all done from within the comfort and convenience of the Visual Studio Integrated Development Environment (IDE), as shown in Figure 5-5. The displayed environment includes four key areas, which I’ve labeled with letters in Figure 5-5: A. The toolbox This listing of controls includes not only display controls, but also controls that expose no specific user interface, such as the Timer. (If you don’t see the tool- box, select the View ➝ Toolbox menu command.) To add a control to a form, double-click the control in the toolbox, drag it from the toolbox to the form, or draw the control on the form after first selecting it from the toolbox. B. The form surface Place any control that exposes a user interface here. The form is WYSIWYG, so you can see the final result as you design the form. Figure 5-5. The Visual Studio environment A B C D Project | 139 C. The Solution Explorer All files related to your project appear here. For the current project, you will see only the My Project entry and an entry for the form, Form1.vb. There are actu- ally more files. If you click the second button from the left at the top of the Solu- tion Explorer, it will show you additional files, most of which are managed by Visual Studio on your behalf. D. The Properties panel When you select a control on your form surface, or the form surface itself, or an item in the Solution Explorer, the properties of the selected item appear in this area. You can alter the settings of many properties by typing in the new setting. Some properties include special tools to assist you in setting the property value. If you haven’t done so already, open the form Form1.vb in design view by double- clicking it in the Solution Explorer. We’ll add eight text labels, three shape and line elements, two web-style hyperlinks, a command button, and a picture to the form’s surface. I’ve already added the picture to the form for you, with an image of some books, naming it SideImage. Set up the form by adjusting the following properties from their defaults. Click on the form surface, and then modify these property values using the Properties panel. Next, add the eight basic text labels to the form’s surface using the Label control. You’ll find this control in the toolbox. As you add each Label control, use the follow- ing list of settings to set the properties for each label. The included text matches my situation, but feel free to modify the content as needed. Property Setting (Name) AboutProgram ControlBox False FormBorderStyle FixedDialog Size 440, 311 StartPosition CenterScreen Text About the Library Project Label name Property settings ProgramName (Name): ProgramName AutoSize: True Font/Bold: True Location: 136, 16 Text: The Library Project ProgramVersion (Name): ProgramVersion AutoSize: True Location: 136, 32 Text: Version X.Y Revision Z 140 | Chapter 5: .NET Assemblies Let’s add some lines and colored sections to the form. Visual Basic 6.0 included dis- tinct shape controls for lines, rectangles, and ellipses that you could apply directly to the form surface. .NET no longer includes these items; you have to add them by hand using source-code-specified drawing commands. * But we can simulate lines and rectangles using the standard Label control, sans the text. LicenseInfo (Name): LicenseInfo AutoSize: False Location: 136, 48 Size: 280, 32 Text: Unlicensed DevelopedBy (Name): DevelopedBy AutoSize: True Location: 136, 88 Text: Developed By DeveloperName (Name): DeveloperName AutoSize: True Location: 160, 112 Text: Tim Patrick DeveloperBook (Name): DeveloperBook AutoSize: True Location: 160, 128 Text: Programming Visual Basic 2008 DeveloperProject (Name): DeveloperProject AutoSize: True Location: 160, 144 Text: In-book Project CompanyCopyright (Name): CompanyCopyright AutoSize: True Location: 136, 208 Text: Copyright (c) 2008 by Tim Patrick. * Microsoft does offer line and shape controls as part of its “Power Packs” for Visual Basic 2005. You’ll find them in the download area of Microsoft’s Visual Basic Development Center, located at http://msdn.microsoft.com/ vbasic. As of this writing, 2008 editions of the Power Packs are not yet available, but the 2005 versions will probably work just fine with Visual Basic 2008. Label name Property settings VersionDivider (Name): VersionDivider AutoSize: False BackColor: Black Location: 136, 80 Size: 280,1 Text: [Don't add any text] BackgroundSide (Name): BackgroundSide AutoSize: False BackColor: White Location: 0, 0 Size: 120, 296 Text: [Don't add any text] Label name Property settings Project | 141 If the BackgroundSide label obscures the graphic, right-click on the label and select Send To Back from the shortcut menu that appears. The LinkLabel control is similar to the more basic Label control, but you can include “links” in the text, clickable sections that are similar to the links on a web page. We’ll use these to display the web site and email address. Add two LinkLabel controls to the form and use the following settings to configure each control’s properties. The final control to add is a button that lets the user close the form. Add a Button control to the form with the following properties. Forms can be configured so that a press of the Esc key triggers a Button control on the form, as though the user was clicking on the button instead of pressing the Esc key. To do this, click on the form surface, and then set its CancelButton property to ActClose. We had to delay this step until the button was actually added to the form; the CancelButton property would not have allowed a setting for a nonexistent button. Well, the form should look pretty good by now. The last thing I like to do is to set up the tab order, the order in which the user accesses each field on the form when press- ing the Tab key on the keyboard. To edit the tab order, select the form surface and then select the View ➝ Tab Order menu command. Each control on the form that can be given a tab order value will suddenly have a tab order number next to it. BackgroundDivider (Name): BackgroundDivider AutoSize: False BackColor: Black Location: 120, 0 Size: 1, 296 Text: [Don't add any text] LinkLabel name Property settings CompanyWeb (Name): CompanyWeb AutoSize: True LinkBehavior: HoverUnderline Location: 160, 160 Text: http://www.timaki.com CompanyEmail (Name): CompanyEmail AutoSize: True LinkBehavior: HoverUnderline Location: 160, 176 Text: tim@timaki.com Button name Property settings ActClose (Name): ActClose DialogResult: Cancel Location: 344, 240 Size: 80, 24 Text: Close Label name Property settings 142 | Chapter 5: .NET Assemblies Click on each number or control in order until you get the arrangement you want. (See Figure 5-6 to view how I ordered the controls.) Finally, select the View ➝ Tab Order menu command again, or press the Esc key, to leave the tab ordering process. You can also set the tab order for each control by modifying its TabIndex property using a zero-based numbering system. However, it’s usually faster to set these values by clicking on each control in order. Adding the Code to the Form Now it’s time to add some real Visual Basic code. Not that we haven’t added any until now. Everything we did on the form, although we didn’t see it happen, was converted into Visual Basic source code. Let’s take a quick look. In the Solution Explorer, click on the Show All Files button, the second button from the left. When all the files appear, click on the “plus sign” next to Form1.vb, and finally, double- click Form1.Designer.vb (see Figure 5-7). Since it’s more than 200 lines of source code bliss, I won’t be printing it here. But look it over; it’s all pretty interesting. As you dragged-and-dropped controls on the form and modified its properties, Visual Studio edited this file on your behalf. It’s part of your form’s class (all forms are classes that derive from System.Windows. Forms.Form ). You can tell by the Partial keyword at the top. Partial Public Class AboutProgram Inherits System.Windows.Forms.Form Figure 5-6. Nice and orderly Project | 143 Most of the action happens in the InitializeComponent procedure. When you are fin- ished looking it all over, close up the designer code and return to the form surface. To make our form a real and interesting form, we need it to do three things: • Show the actual version number of the application. This should be determined and displayed right when the form first appears. • Jump to the appropriate web site or email recipient when clicking on the link labels. These events get processed in response to a user action. • Close the form when the user clicks the Close button. This is also a user-driven event. Let’s start with the easy one, closing the form. I’m sure you remember about events from Chapter 1. Events are blocks of code that are processed in response to some- thing happening, most often a user action such as a mouse click. All of the actions we want to perform on this form will be in response to a triggered event (lucky us). The easiest way to get to the “default” event for a control is to double-click the con- trol. Try it now; double-click the Close button. When you do, the IDE opens the source code view associated with the form, and adds an empty event handler (the ActClose_Click subroutine). Public Class AboutProgram Private Sub ActClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ActClose.Click End Sub End Class Every forms-based event (and in fact, most other types of events) in .NET has pretty much the same arguments: (1) a sender argument that indicates which object trig- gered this event; and (2) the e argument, which allows sender to supply any additional Figure 5-7. Accessing the hidden, secret, forbidden code—yeah, it’s out there Click here Then here Double-click here 144 | Chapter 5: .NET Assemblies information that may be useful in the event. In this case, the sender argument will be a reference to the ActClose button, since that’s the object that will generate the Click event. A button’s Click event doesn’t have any more useful information available, so e is the default object type, System.EventArgs, which is pretty much just a place- holder, and the object from which all of the more interesting e argument types derive. The name of this event handler is ActClose_Click, but if you want to change it to FredAndWilma, that’s fine; it won’t mess up anything. But you must keep the Handles ActClose.Click clause intact. This is the part that links the event handler to the actual event. The code to close the form is extremely simple. Enter it now, either by using the first code snippet for this chapter or by typing it directly. INSERT SNIPPET Insert Chapter 5, Snippet Item 1. ' Close the form. Me.Close( ) This statement says, “I’m the AboutProgram form/object, and I command myself to close.” If you run the program right now (press the F5 key), you close the form by clicking on the Close button. Since the AboutProgram form was the only form in the application, closing it automatically ended the entire application, no questions asked. OK, back up to the second item, the web-style links. You could go back to the form surface and double-click on each link label to create an event handler for each label’s default event (in this case, the LinkClicked event). But you can also add the event handler subroutines right in the editor, either by typing the code yourself (which is no fun) or by using the two drop-down lists just above the editor window (see Figure 5-8). The Class Name list appears on the left side. Selecting an entry from this list updates the righthand list, the Method Name list. To add an event handler template for the CompanyWeb’s LinkClicked event, first select CompanyWeb from the Class Name list, Figure 5-8. The Class Name and Method Name fields Project | 145 and then select LinkClicked from the Method Name list. The following code block appears in the code window: Private Sub CompanyWeb_LinkClicked(ByVal sender As Object, _ ByVal e As System.Windows.Forms. _ LinkLabelLinkClickedEventArgs) _ Handles CompanyWeb.LinkClicked End Sub This template’s argument list is a little more interesting, since its e argument is an object of type System.Windows.Forms.LinkLabelLinkClickedEventArgs. The LinkLabel control allows you to have multiple web-style links in a single control, interspersed among regular text. The e argument has a Link property that tells you which of the links in the control was clicked by the user. Since our labels have only a single link, we won’t bother to check it. We’ll just show the web page immediately anytime the link is clicked. INSERT SNIPPET Insert Chapter 5, Snippet Item 2. ' Show the company web page. Process.Start("http://www.timaki.com") The Process object is part of the System.Diagnostics namespace, and Start is one of its shared members that lets you start up external applications and resources. You pass it any valid URL and it will run using the user’s default browser or application for that URL. Let’s try it again with the CompanyEmail’s LinkClicked event. Add in the template any way you choose and then type or insert the code that starts a new mes- sage to an email address. INSERT SNIPPET Insert Chapter 5, Snippet Item 3. ' Send email to the company. Process.Start("mailto:tim@timaki.com") The last event to design is one of the first events called in the lifetime of the form: the Load event. It’s called just before the form appears on the screen. Double-clicking on the surface of the form creates an event handler template for the Load event. If you prefer to use the Class Name and Method Name drop-down lists instead, select (AboutProgram Events) from the Class Name list before using the Method Name list. Private Sub AboutProgram_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load End Sub 146 | Chapter 5: .NET Assemblies Let’s add code to this event handler that displays the correct version number, using the version information found in My.Application.Info.Version, an instance of the System.Version class. INSERT SNIPPET Insert Chapter 5, Snippet Item 4. ' Update the version number. With My.Application.Info.Version ProgramVersion.Text = "Version " & .Major & "." & _ .Minor & " Revision " & .Revision End With This code uses a With statement to reduce the amount of typing needed in the main assignment statement. Inside the With End With statement, you aren’t required to retype the object name that appears just after the With keyword—in this case, My.Application.Info.Version. You can just refer to that object’s members by typing a dot ( .) followed by the name of the member. You could forgo the With statement and type the full object name each time you wanted to use one of the ver- sion values, but this way keeps the code cleaner and less overwhelming. Setting the Version Number If you run the program, it will display the currently defined version number, “1.0 Revision 0,” as shown in Figure 5-9. My question—and I hope I can answer it before the paragraph is finished—is, “Where is that version number defined, and how can it be changed?” It turns out that I do know the answer: the version values are stored as metadata within the assembly. Visual Studio includes a form that lets you modify the basic informational metadata stored in the assembly. To access the form, display the project’s properties (double-click on My Project in the Solution Explorer), select the Application tab, and then click on the Assembly Information button (see Figure 5-10). Our AboutProgram form displays the assembly’s version number, which is set using the four text fields next to the Assembly Version label. Those four fields represent the Major, Minor, Build, and Revision numbers of the assembly. Go ahead, set them to some other values, click OK, and run the program again. Figure 5-9. The version number from the AboutProgram form [...]... smaller 0.25; 1 /3 became 0 .33 333 333 333 333 333 333 333 333 333 333 333 3 33 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 33 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 3 hey, what’s going on here? I can’t write all those 3s The book would be 2,000 pages, or more Eventually people discovered that in many cases, it just wasn’t worth the bother of writing out all the 3s, so they... 255 System.SByte 8 Signed –128 to 127 System.Int16 16 Signed 32 ,768 to 32 ,767 System.UInt16 16 Unsigned 0 to 65, 535 System.Int32 32 Signed –2,147,4 83, 648 to 2,147,4 83, 647 System.UInt32 32 Unsigned 0 to 4,294,967,295 System.Int64 64 Signed –9,2 23, 372, 036 ,854,775,808 to 9,2 23, 372, 036 ,854,775,807 System.UInt64 64 Unsigned 0 to 18,446,744,0 73, 709,551,615 Looking at these types another way, Table 6-2 shows... the left of the decimal, the fewer you have available for the right of the decimal, and vice versa For numbers with no decimal portion, the range is from –79,228,162,514,264 ,33 7,5 93, 5 43, 950 ,33 5 to 79,228,162,514,264 ,33 7,5 93, 5 43, 950 ,33 5 (That’s 29 digits, but who’s counting?) For numbers with only zero (0) to the left of the decimal, the range is –0.0000000000000000000000000001 to 0.0000000000000000000000000001... comes with a substantial performance hit Visual Basic Data Types All the data types implemented in the Visual Basic language are wrappers for the core NET data types Only some of the names have been changed to protect the innocent Table 6-5 lists the Visual Basic data types and their NET equivalents Table 6-5 Visual Basic data types and related NET types Visual Basic type NET type Boolean System.Boolean... 0.00000000000 23 It’s close to zero, but not exactly zero But you can use very large or very small numbers For negative values, the range is 3. 402823E +38 to –1.401298E–45; for positive values, its range is 1.401298E–45 to 3. 402823E +38 System.Double Imperfect Huge The Double data type is just like the Single data type, but with a bigger attitude—I mean a larger range For negative values, the range is –1.7976 931 3486 231 E +30 8... Double data type is just like the Single data type, but with a bigger attitude—I mean a larger range For negative values, the range is –1.7976 931 3486 231 E +30 8 to –4.94065645841247E 32 4; for positive values, the range is 4.94065645841247E 32 4 to 1.7976 931 3486 232 E +30 8 Data in NET | 155 Character Data Types Hey, check this out ktuefghbiokh Pretty cool, eh? That’s the power of a computer in action managing text... those 3s The book would be 2,000 pages, or more Eventually people discovered that in many cases, it just wasn’t worth the bother of writing out all the 3s, so they just stopped at some point, as in 0 .33 333 333 It wasn’t perfectly accurate, but it was good enough This is what life is like for computer-based decimal values You can have perfect accuracy—up to a point After that, you have to settle for good... Data and Data Types Table 6-5 Visual Basic data types and related NET types (continued) Visual Basic type NET type Decimal System.Decimal Double System.Double Integer System.Int32 Long System.Int64 Object System.Object SByte System.SByte Short System.Int16 Single System.Single String System.String UInteger System.UInt32 ULong System.UInt64 UShort System.UInt16 All the Visual Basic data types are fully... any format recognized by Windows, although Visual Studio may reformat your date literal for conformity with its own standards Decimal 1 23. 45D 1 23. 45@ Floating-point values of type Decimal are followed by a capital D, or the character @ Literals | 159 Table 6-6 Literals supported by Visual Basic (continued) Literal type Example Description Double 1 23. 45R 1 23. 45# Floating-point values of type Double... for a variable But a new Visual Basic 2008 feature called local type inference lets the Visual Basic compiler join in the fun of assigning data types to variables And what fun it is! In standard variable declaration, you include the data type with an As clause Dim whatAmI As String whatAmI = "You're a string, and nothing but a string." But with local type inference, Visual Basic will figure out the . 0.25; 1 /3 became 0 .33 333 333 333 333 333 333 333 333 333 333 333 3 33 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 33 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 333 3 hey,. 32 ,768 to 32 ,767 System.UInt16 16 Unsigned 0 to 65, 535 System.Int32 32 Signed –2,147,4 83, 648 to 2,147,4 83, 647 System.UInt32 32 Unsigned 0 to 4,294,967,295 System.Int64 64 Signed –9,2 23, 372, 036 ,854,775,808. numbers with no decimal portion, the range is from –79,228,162,514,264 ,33 7,5 93, 5 43, 950 ,33 5 to 79,228,162,514,264 ,33 7,5 93, 5 43, 950 ,33 5. (That’s 29 digits, but who’s counting?) For numbers with only

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

Từ khóa liên quan

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

Tài liệu liên quan