Beginning microsoft Visual Basic 2010 phần 7 pdf

72 383 0
Beginning microsoft Visual Basic 2010 phần 7 pdf

Đ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

398 ❘ CHAPTER 12 ADVANCED OBJECT-ORIENTED TECHNIQUES ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ Handles lnkUrl.LinkClicked ‘Process the selected link Process.Start(e.Link.LinkData) End Sub 3. Run the project. You should now see that when a URL is selected from the list, the LinkLabel con- trol changes to reflect the name of the selected item (refer to Figure 12-4). When you click the link, Internet Explorer opens the URL in the LinkLabel control’s LinkCollection. How It Works Now that you have the application working in this example, let’s look at how it works. When you click an item in the ListView control, the Click event is fired for that control. You add code to the Click event to load the LinkLabel control with the selected link. You start by first setting the Text property of the LinkLabel control. This is the text that will be displayed on the form as shown in Figure 12-4. You set the Text property using the static text Visit followed by the actual favorite name. The favorite name is retrieved from the ListView control’s Item collection. Each row in the ListView control is called an item, and the first column contains the text of the item. Each column past the first column in a row is a subitem of the item (the text in the first column). The text that gets displayed in the link label is taken from the Text property of the Item collection: Private Sub lvwFavorites_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles lvwFavorites.Click ‘Update the link label control Text property lnkUrl.Text = "Visit " & lvwFavorites.SelectedItems.Item(0).Text The Links property of the LinkLabel control contains a LinkCollection that contains a default hyperlink consisting of the text that is displayed in the LinkLabel control. You clear this collection and set it using the correct hyperlink for the selected Favorite. You do this by calling the Clear method on the Links property: ‘Clear the default hyperlink lnkUrl.Links.Clear() Finally, you add your hyperlink using the subitem of the selected item in the ListView control. The Add method of the Links property is an overloaded method, and the method that you are using here expects three parameters: start , length ,and linkdata .The start parameter specifies the starting position of the text in the Text property that you want as the hyperlink, and the length parameter specifies how long the hyperlink should be. You do not want the word Visit to be part of the hyperlink, so you specify the starting position to be 6 , which takes into account the space after the word Visit. Then you specify the length parameter using the Length property of the Text property of the selected item in the ListView control. Finally, you specify the linkdata parameter by specifying the selected subitem from the ListViewlist view control. This subitem contains the actual URL for the favorite. ‘Add the selected hyperlink to the LinkCollection lnkUrl.Links.Add(6, lvwFavorites.SelectedItems.Item(0).Text.Length, _ lvwFavorites.SelectedItems.Item(0).SubItems(1).Text) End Sub    An Alternative Favorite Viewer ❘ 399 When a hyperlink on the LinkLabel control is clicked, it fires the LinkClicked event, and this is where you place your code to process the hyperlink of the favorite being displayed in this control. The LinkLabelLinkClickedEventArgs class contains information about the link label and, in particular, the actual hyperlink in the LinkCollection . To retrieve the hyperlink, you access the LinkData property of the Link property. Then you pass this data to the Start method of the Process class, which causes a browser to be open and display the selected hyperlink: Private Sub lnkUrl_LinkClicked(ByVal sender As Object, _ ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ Handles lnkUrl.LinkClicked ‘Process the selected link Process.Start(e.Link.LinkData) End Sub AN ALTERNATIVE FAVORITE VIEWER You know that building separate classes promotes code reuse, but let’s prove that. If code reuse is such a hot idea, without having to rewrite or change any of the code you should be able to build another application that can use the functionality in the classes to find and open favorites. In this case, you might have given a colleague the Favorites , WebFavorite ,and WebFavoriteCollection classes, and that colleague should be able to build a new application that uses this functionality without having to understand the internals of how Internet shortcuts work or how Windows stores the user’s favorites. Building a Favorites Tray In this section, you build an application that displays a small icon on the system tray. Clicking this icon opens a list of the user’s favorites as a menu, as shown in Figure 12-7. Clicking a favorite automatically opens the URL in Internet Explorer or whatever browser the user has set to be the default. Later, when you see Internet Explorer, it may be a different browser for you. FIGURE 12-7 To demonstrate this principle of code reuse, you need to create a new Visual Basic 2010 project in this solution.    400 ❘ CHAPTER 12 ADVANCED OBJECT-ORIENTED TECHNIQUES TRY IT OUT Building a Favorites Tray Code file Favorites.zip is available for download at Wrox.com In this example, you will add a new project 1. Using Visual Studio 2010, select File ➪ Add ➪ New Project from the menu and create a new Visual Basic 2010 Windows Forms Application project called Favorites Tray.Now,youwillseetwo projects in the Solution Explorer. 2. When the Designer for Form1 appears, click the form in the Forms Designer and then change the WindowState property to Minimized and change the ShowInTaskbar property to False. This, effec- tively, prevents the form from being displayed. 3. Using the Toolbox, drag a NotifyIcon control onto the form. It will drop into the component tray at the bottom of the form. Set the Name property of the new control to icnNotify and set the Text property to Right-click me to view Favorites, and set the Icon property to C:\Program Files\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary\1033\VS2010ImageLibrary\ Objects\ico_format\WinVista\Favorites.ico . 4. Next, open the Code Editor for Form1. In the Class Name combo box at the top of the Code Edi- tor, select (Form1 Events), and in the Method Name combo box select VisibleChanged.Addthe following highlighted code to the event handler: Private Sub Form1_VisibleChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.VisibleChanged ‘If the user can see us, hide us If Me.Visible = True Then Me.Visible = False End Sub FIGURE 12-8 figure 5. Right-click the Favorites Tray project in the Solution Explorer and select Set As Startup Project. Now try running the project. You should discover that the tray icon is added to your system tray as shown in Figure 12-8, but no form window will appear. If you hover your mouse over the icon, you’ll see the message that you set in the Text property of the NotifyIcon control. 6. Also, you’ll notice that there appears to be no way to stop the program! Flip back to Visual Studio 2010 and select Debug ➪ Stop Debugging from the menu. 7. When you do this, although the program stops, the icon remains in the tray. To get rid of it, hover the mouse over it and it should disappear. Windows redraws the icons in the system tray only when necessary (for example, when the mouse is passed over an icon). How It Works You learn that setting a form to appear minimized ( WindowState = Minimized ) and telling it not to appear in the taskbar ( ShowInTaskbar = False ) has the effect of creating a window that’s hidden in this example. You need a form to support the tray icon, but you don’t need the form for any other reason. However, this is only half the battle, because the form could appear in the Alt+Tab application switching list, unless you add the following code, which you already did: Private Sub Form1_VisibleChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.VisibleChanged    An Alternative Favorite Viewer ❘ 401 ‘If the user can see us, hide us If Me.Visible = True Then Me.Visible = False End Sub This event handler has a brute-force approach that says, ‘‘If the user can see me, hide me.’’ Displaying Favorites In the next Try It Out, you look at how to display the favorites. TRY IT OUT Displaying Favorites Code file Favorites.zip is available for download at Wrox.com In this example, the first thing you need to do is include the classes built in Favorites Viewer in this Favorites Tray solution. You can then use the Favorites object to get a list of favorites back and build a menu. 1. To display favorites, you need to get hold of the classes defined in the Favorites Viewer project. To do this you add the Favorites , WebFavorite ,and WebFavoriteCollection classes to this project. Using the Solution Explorer, right-click the Favorites Tray project and select Add ➪ Existing Item. Browse to the classes in your Favorites Viewer project and find the Favorites class. After clicking Add, the class appears in the Solution Explorer for this project. You can select multiple files at once by holding down the Ctrl key. 2. Repeat this for the WebFavorite and WebFavoriteCollection classes. 3. Create a new class in the Favorites Tray by clicking the project once more and selecting Add ➪ Class. Call the new class WebFavoriteMenuItem.vb and then click the Add button to add this class to the project. 4. Set the new class to inherit from System.Windows.Forms.MenuItem by adding this code: Public Class WebFavoriteMenuItem Inherits MenuItem 5. Add this member and method to the class: ‘Public member Public Favorite As WebFavorite ‘Constructor Public Sub New(ByVal newFavorite As WebFavorite) ‘Set the property Favorite = newFavorite ‘Update the text Text = Favorite.Name End Sub 6. Unlike ListViewItem , MenuItem objects can react to themselves being clicked by overload- ing the Click method. In the Class Name combo box at the top of the Code Editor, select    402 ❘ CHAPTER 12 ADVANCED OBJECT-ORIENTED TECHNIQUES ( WebFavoriteMenuItem Events) and then select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler: Private Sub WebFavoriteMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Click ‘Open the favorite If Not Favorite Is Nothing Then Process.Start(Favorite.Url) End If End Sub 7. You need to do a similar trick to add an Exit option to your pop-up menu. Using the Solution Explorer, create a new class called ExitMenuItem.vb in the Favorites Tray project. Add the fol- lowing highlighted code to this class: Public Class ExitMenuItem Inherits MenuItem ‘Constructor Public Sub New() Text = "Exit" End Sub Private Sub ExitMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Click Application.Exit() End Sub End Class 8. Finally, you’re in a position where you can load the favorites and create a menu for use with the tray icon. Add these members to Form1: Public Class Form1 ‘Public member Public Favorites As New Favorites() ‘Private member Private blnLoadCalled As Boolean = False 9. In the Class Name combo select (Form1 Events), and in the Method Name combo box, select the Load event. Then add the following highlighted code to this event handler: Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load ‘Load the favorites Favorites.ScanFavorites() ‘Create a new context menu Dim objMenu As New ContextMenu() ‘Process each favorite For Each objWebFavorite As WebFavorite In Favorites.FavoritesCollection ‘Create a menu item Dim objItem As New WebFavoriteMenuItem(objWebFavorite)    An Alternative Favorite Viewer ❘ 403 ‘Add it to the menu objMenu.MenuItems.Add(objItem) Next ‘Add a separator menu item objMenu.MenuItems.Add("-") ‘Now add the Exit menu item objMenu.MenuItems.Add(New ExitMenuItem()) ‘Finally, tell the tray icon to use this menu icnNotify.ContextMenu = objMenu ‘Set the load flag and hide ourselves blnLoadCalled = True Me.Hide() End Sub 10. Modify the Form1_VisibleChanged procedure as follows: Private Sub Form1_VisibleChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.VisibleChanged ‘Don’t set the Visible property until the Load event has ‘been processed If blnLoadCalled = False Then Return End If ‘If the user can see us, hide us If Me.Visible = True Then Me.Visible = False End Sub 11. Run the project, and the icon will appear on the system tray. Right-click the icon, and you’ll see a list of favorites as was shown in Figure 12-7. Clicking one opens Internet Explorer; clicking Exit closes the application. Depending on what applications you have open and your settings, the icon may be grouped in the hidden icon section on the taskbar. How It Works That completes this example. One thing to note is that because of the order of events that are fired for your form, you have to create a variable in Form1 called blnLoadCalled . This variable makes sure that your favorites get loaded in the form’s Load event. The WebFavoriteMenuItem class accepts a WebFavorite object in its constructor, and it configures itself as a menu item using the class. However, this class provides a Click method that you can overload, so when the user selects the item from the menu, you can immediately open the URL: Private Sub WebFavoriteMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Click ‘Open the favorite If Not Favorite Is Nothing Then Process.Start(Favorite.Url) End If End Sub    404 ❘ CHAPTER 12 ADVANCED OBJECT-ORIENTED TECHNIQUES The ExitMenuItem class does a similar thing. When this item is clicked, you call the shared Application.Exit method to quit the program: Private Sub ExitMenuItem_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Click Application.Exit() End Sub The important thing here is not the construction of the application itself but rather the fact that you can reuse the functionality you built in a different project. This underlines the fundamental motive for reuse; it means you don’t have to reinvent the wheel every time you want to do something. The method of reuse described here was to add the existing classes to your new project, hence making a second copy of them. This isn’t efficient, because it takes double the amount of storage needed for the classes; however, the classes are small, so the cost of memory is minimal. It did save you from having to create the classes from scratch, allowing you to reuse the existing code, and it was very easy to do. An alternative way of reusing classes is to create them in a class library. This class library is a separate project that can be referenced by a number of different applications so that only one copy of the code is required. This is discussed in Chapter 13. USING SHARED PROPERTIES AND METHODS On occasion, you might find it useful to access methods and properties that are not tied to an instance of an object but are still associated with a class. Imagine you have a class that stores the user name and password of a user for a computer program. You might have something that looks like this: Public Class User ‘Public members Public Username As String ‘Private members Private strPassword As String End Class Now imagine that the password for a user has to be of a minimum length. You create a separate mem- ber to store the length and implement a property like this: Public Class User ‘Public members Public Username As String Public MinPasswordLength As Integer = 6 ‘Private members Private strPassword As String ‘Password property Public Property Password() As String Get    Using Shared Properties and Methods ❘ 405 Return strPassword End Get Set(ByVal value As String) If value.Length >= MinPasswordLength Then strPassword = value End If End Set End Property End Class That seems fairly straightforward. But now imagine that you have five thousand user objects in mem- ory. Each MinPasswordLength variable takes up 4 bytes of memory, meaning that 20 KB of memory is being used to store the same value. Although 20 KB of memory isn’t a lot for modern computer systems, it’s extremely inefficient, and there is a better way. Using Shared Properties See how to use shared properties and understand them in the next example. TRY IT OUT Using Shared Properties Code file Shared Demo.zip is available for download at Wrox.com Ideally, you want to store the value for the minimum password length in memory against a specific class once and share that memory between all of the objects created from that class, as you’ll do in the following Try It Out. 1. Close the existing solution if it is still open and create a new Windows Forms Application project called Shared Demo. FIGURE 12-9 figure 2. When the Designer for Form1 appears, change the Text prop- erty of the form to Shared Demo and then drag a ListBox, a Label, and a NumericUpDown control from the Toolbox onto the form. Set the Text property of the Label to Password Length. Arrange the controls as shown in Figure 12-9. 3. Set the Name property of the ListBox control to lstUsers. 4. Set the Name property of the NumericUpDown control to nud- MinPasswordLength,setthe Maximum property to 10,andset the Value property to 6. 5. Using the Solution Explorer, create a new class named User . Add the highlighted code to the class: Public Class User ‘Public members Public Username As String Public Shared MinPasswordLength As Integer = 6    406 ❘ CHAPTER 12 ADVANCED OBJECT-ORIENTED TECHNIQUES ‘Private members Private strPassword As String ‘Password property Public Property Password() As String Get Return strPassword End Get Set(ByVal value As String) If value.Length >= MinPasswordLength Then strPassword = value End If End Set End Property End Class 6. View the code for Form1 and add this highlighted member: Public Class Form1 ‘Private member Private arrUserList As New ArrayList() 7. Add this method to the Form1 class: Private Sub UpdateDisplay() ‘Clear the list lstUsers.Items.Clear() ‘Add the users to the list box For Each objUser As User In arrUserList lstUsers.Items.Add(objUser.Username & ", " & objUser.Password & _ " (" & User.MinPasswordLength & ")") Next End Sub 8. Select (Form1 Events) in the Class Name combo box at the top of the Code Editor and the Load event in the Method Name combo box. Add the highlighted code to the Load event: Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load ‘Load 100 users For intIndex As Integer = 1 To 100 ‘Create a new user Dim objUser As New User objUser.Username = "Stephanie" & intIndex objUser.Password = "password15" ‘Add the user to the array list arrUserList.Add(objUser) Next ‘Update the display UpdateDisplay() End Sub    Using Shared Properties and Methods ❘ 407 9. Select nudMinPasswordLength in the Class Name combo box at the top of the Code Editor and the ValueChanged event in the Method Name combo box. Add the highlighted code to the ValueChanged event: Private Sub nudMinPasswordLength_ValueChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles nudMinPasswordLength.ValueChanged ‘Set the minimum password length User.MinPasswordLength = nudMinPasswordLength.Value ‘Update the display UpdateDisplay() End Sub FIGURE 12-10 figure 10. Save your project by clicking the Save All button on the tool- bar. 11. Run the project. You should see a screen like the one shown in Figure 12-10. 12. Scroll the NumericUpDown control up or down, and the list updates; the number in parentheses changes to cor- respond to the number shown in the NumericUpDown control. How It Works To create a member variable, property, or method on an object that is shared, you use the Shared keyword as you did in this example. Public Shared MinPasswordLength As Integer = 6 This tells Visual Basic 2010 that the item should be available to all instances of the class. Shared members can be accessed from within nonshared properties and methods as well as from shared properties and methods. For example, here’s the Password property, which can access the shared MinPasswordLength member: ‘Password property Public Property Password() As String Get Return strPassword End Get Set(ByVal value As String) If value.Length >= MinPasswordLength Then strPassword = value End If End Set End Property What’s important to realize here is that although the Password property and strPassword member belong to the particular instance of the User class, MinPasswordLength does not; therefore, if it is changed the effect is felt throughout all the object instances built from the class in question.    [...]... new key pair From the Windows Start menu select All Programs ➪ Microsoft Visual Studio 2010 ➪ Visual Studio Tools ➪ Visual Studio 2010 Command Prompt NOTE If you are running on Windows Vista or Windows 7, you will most likely need to run the command prompt with administrator privileges To do this, instead of left-clicking the Visual Studio 2010 Command Prompt, right-click it and choose Run As Administrator... create a Windows Forms application, Visual Studio 2010 knows that you will be compiling it into a program that can run When you choose a class library, Visual Studio 2010 knows that the resulting library will not be run on its own, so the choices you make here affect what Visual Studio 2010 does when you build the project Selecting a class library means that Visual Studio 2010 will build the project into... email0 REISEMAN 071 @COMCAST.NET Order number0 5 577 1330 This PDF is for the purchaser’s personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book’s copyright page If you did not purchase this copy/ please visit www.wrox.com to purchase your own copy Prepared for STEPHEN EISEMAN/ email0 REISEMAN 071 @COMCAST.NET Order number0 5 577 1330 This PDF is for the purchaser’s... and revision number will be generated by Visual Studio 2010 Every time you recompile the assembly, Visual Basic 2010 will adjust these numbers to ensure that every compilation has a unique version number You could choose to replace the build and revision numbers with your own hard-coded numbers and increment them yourself, but if you’re happy with Visual Basic 2010 s decision, then you can just leave... Vista, and Windows 7) Gacutil Utility Gacutil.exe is a utility provided with the NET Framework for installing/uninstalling GAC assemblies via a command line From the Windows Start menu, select Programs → Microsoft Visual Studio 2010 ➪ Visual Studio Tools ➪ Visual Studio 2010 Command Prompt Navigate to the bin folder for your Internet Favorites Prepared for STEPHEN EISEMAN/ email0 REISEMAN 071 @COMCAST.NET... when it needs to be used However, this would be very slow Instead, the Visual Basic 2010 compiler takes a hash of the assembly and encrypts that using the private key If anybody tries to tamper with the assembly, the hash will cease to be valid Prepared for STEPHEN EISEMAN/ email0 REISEMAN 071 @COMCAST.NET Order number0 5 577 1330 This PDF is for the purchaser’s personal use in accordance with the Wrox Terms... text SUMMARY Class libraries are an integral part of Visual Basic 2010; they are important to all of the languages in the NET Framework They encompass what you use and what you need to know in terms of the common language runtime and within your development projects Prepared for STEPHEN EISEMAN/ email0 REISEMAN 071 @COMCAST.NET Order number0 5 577 1330 This PDF is for the purchaser’s personal use in accordance... move the classes from the Windows Forms Application project to the Class Library project 1 2 3 4 5 Switch to the instance of Visual Studio 2010 containing the Internet Favorites project Save the project and then close Visual Studio 2010 Switch to the instance of Visual Studio 2010 containing the Favorites Viewer project Click the File ➪ Add ➪ Existing Project Navigate to where you saved your Internet... used within Visual Basic 2010, you can use a quick and easy tool known as the Object Browser You can also use the Object Browser to view class names and method names on objects The Object Browser window can be viewed inside Visual Studio 2010 by pressing F2 It is also available by selecting View → Object Browser, or by clicking the Object Browser icon on the toolbar The Object Browser is basically used... basically used for a quick reference to the classes you need to see It will show all assemblies that are used in the current solution, including Visual Basic projects and compiled DLLs Prepared for STEPHEN EISEMAN/ email0 REISEMAN 071 @COMCAST.NET Order number0 5 577 1330 This PDF is for the purchaser’s personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book’s copyright . this example, you will add a new project 1. Using Visual Studio 2010, select File ➪ Add ➪ New Project from the menu and create a new Visual Basic 2010 Windows Forms Application project called Favorites. to view Favorites, and set the Icon property to C:Program Files Microsoft Visual Studio 10.0Common7VS2010ImageLibrary1033VS2010ImageLibrary Objectsico_formatWinVistaFavorites.ico . 4 Explorer, it may be a different browser for you. FIGURE 12 -7 To demonstrate this principle of code reuse, you need to create a new Visual Basic 2010 project in this solution.    400 ❘ CHAPTER

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

Từ khóa liên quan

Mục lục

  • WroxBooks

    • Beginning Microsoft® Visual Basic® 2010

      • Chapter 12: Advanced Object-Oriented Techniques

        • AN ALTERNATIVE FAVORITE VIEWER

        • USING SHARED PROPERTIES AND METHODS

        • UNDERSTANDING OBJECT-ORIENTED PROGRAMMING AND MEMORY MANAGEMENT

        • SUMMARY

        • Chapter 13: Building Class Libraries

          • UNDERSTANDING CLASS LIBRARIES

          • USING STRONG NAMES

          • REGISTERING ASSEMBLIES

          • DESIGNING CLASS LIBRARIES

          • USING THIRD-PARTY CLASS LIBRARIES

          • VIEWING CLASSES WITH THE OBJECT BROWSER

          • SUMMARY

          • Chapter 14: Creating Windows Forms User Controls

            • WINDOWS FORMS CONTROLS

            • CREATING AND TESTING A USER CONTROL

            • EXPOSING PROPERTIES FROM USER CONTROLS

            • DESIGN TIME OR RUNTIME

            • CREATING A COMMAND LINK CONTROL

            • SUMMARY

            • Chapter 15: Accessing Databases

              • WHAT IS A DATABASE?

              • THE SQL SELECT STATEMENT

              • QUERIES IN ACCESS

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

Tài liệu liên quan