Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 (2006)

.pdf
Скачиваний:
219
Добавлен:
17.08.2013
Размер:
14.97 Mб
Скачать

Chapter 12

Do not overexert yourself by adding every conceivable method and functional enhancement that an object can have; rather think ahead but code later. You can easily complicate matters for your developers by granting them too many choices, and, at the same time, you may be adding functionality that will never be used.

Try to keep classes within your library to a minimum, because better reuse comes from keeping your libraries smaller.

Properties are extremely useful in a class, and they enable it to be used more easily.

Using Third-Par ty Class Libraries

A class library compiles to a .dll file. To use the class library you need only the DLL, you don’t need the source code. This means that you can give your DLL to other people to use and you can use other people’s DLLs in your own applications. To demonstrate how to use a DLL, you’re going to use the InternetFavorites.dll file that you created in the next Try It Out.

Using InternetFavorites.dll

You’ve already seen how to create references to other projects in a solution. This is a really good way to develop and test class libraries and applications at the same time. In this example you’re going to pretend that you didn’t create InternetFavorites.dll. You’re going to modify the Favorites Tray application so that it uses InternetFavorites.dll. This is a very quick way to demonstrate the use of DLLs, but remember that in real life you would add a reference to the DLL early on in developing the application and then write code to use the DLL.

Try It Out

Using FavoritesLib.dll in the Favorites Tray Application

1.Open the Favorites Tray project.

2.Delete the following files from the project: Favorites.vb, WebFavorite.vb, and Web FavoriteCollection.vb.

3.Now you need to add a reference to InternetFavorites.dll. Right-click the Favorites Tray project and select Add Reference. Scroll down the list of components in the .NET tab until you find InternetFavorites. Select it and then click the OK button to close the Add Reference dialog box.

4.Remember that the classes in the class library are in the InternetFavorites namespace, so you need to tell your code to look in that namespace for class names you use. Add the following Imports statement to the top of Form1.vb and WebFavoriteMenuItem.vb:

Imports InternetFavorites

You do not need to add it to ExitMenuItem.vb because this class does not use any of the classes in the library.

5.Run the program. It will work as normal, but will be using the class library now instead of classes within the application’s .exe file.

396

Building Class Libraries

How It Works

This process works more easily than adding a reference to another project does. You still use the classes in the class library in exactly the same way regardless of whether you reference the Class Library project or the compiled DLL. The main difference is that you cannot see or edit the class library’s source code.

However, the Visual Studio 2005 environment can still tell a lot about the classes even without the source code. For example, IntelliSense still works. This is because Visual Studio 2005 can tell from the DLL itself what methods and properties are available on each class. You can investigate a class without using IntelliSense but using the Object Browser.

Viewing Classes with the Object Browser

To view classes that can be used within Visual Basic 2005, 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 2005 by pressing F2. It is also available by clicking the View Object Browser menu or by clicking the Object Browser icon on the toolbar.

The Object Browser is basically used for a quick reference to the classes you need to see. The Object Browser will show all assemblies that are used in the current Solution, including Visual Basic Projects and compiled DLLs.

The browser shows all members including methods, enumerations, and constants. Each member type is shown with a different icon. Figure 12-7 shows the InternetFavorites.Favorites class. You select this class by choosing the InternetFavorites assembly and then within that the InternetFavorites namespace and then within that the Favorites class.

Figure 12-7

Remember that an assembly can contain several namespaces and that the same namespace can be spread across several assemblies. It just happens that in Visual Basic 2005 you normally have a single namespace inside a single assembly of the same name.

397

Chapter 12

The MSDN Library documentation that gets installed with Visual Studio 2005 contains plenty of information about classes in the .NET Framework, so you don’t often need to use the Object Browser when you’re using only .NET Framework classes. It is really useful, however, when you are using a DLL from a third party that does not come with documentation. Often the method and property names can give you a clue about what’s happening. Of course, this underlines why it is necessary to choose good names for your classes and their members.

On other occasions, the DLL will provide short descriptions of each of its classes and members. This is done using attributes, which is a subject outside the scope of this text.

Summar y

Class libraries are an integral part of Visual Basic 2005 and, in fact, 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.

In this chapter, you have considered the nature of class libraries and how to view the properties and methods contained within them using the Object Browser. You have also seen how the .NET Framework allows developers to avoid DLL Hell through the use of keys and signatures, and looked at some of the broad issues regarding designing your own components.

In Chapter 13, you will learn how to create Windows Forms controls that are components with a user interface, as opposed to class library projects, which are purely code-based. There too, you will see the importance of reusable and stable code.

Exercise

Modify the Favorites Viewer project to use the compiled InternetFavorites.dll instead of the InternetFavorites project.

398

13

Creating Your Own

Custom Controls

In this book, you have used many of the controls that come with the .NET Framework, from the Button and the TextBox controls to the ListBox control. You may even have tried to use some of the more advanced controls such as the DataGrid and the TreeView controls. Although at first some of them may be hard to use, they offer a lot of functionality. These controls make it easy to create a user interface in your applications. Once you get to know how to use all their features, you will find that creating user interfaces also becomes a faster experience. Another important aspect that makes controls so useful is that they are reusable. You can drag and drop a Button control onto any form in any new Windows project and it works as a button should. The reuse factor is an important reason why Visual Basic, in general, became one of the most popular and is presently, one of the most powerful development languages in use today. Did you know that you owe much of what you experience today in Visual Studio 2005, like Windows Forms Controls, to Visual Basic? The history of Windows Forms Controls has roots in something known as controls Visual Basic Extension (VBX). This later became more widely known as ActiveX, and today, revitalized and reborn into the .NET Framework, it is known as Windows Forms Controls.

In this chapter, you will:

Learn what a Windows Forms Control is and how it works

Create and use a Windows Forms Control

Learn to add methods and events to your control

Learn to code for design time and run time

These controls are best suited for Windows Forms rather than Web Applications. To learn about Web Server controls you should turn to Chapter 18. This chapter will concentrate on the Windows Forms version.

Chapter 13

Windows Forms Controls

Today, there are several good reasons for wanting to create Windows Forms Controls:

You can use the same control throughout an application or in lot of different applications, thus saving on code (reuse).

You can keep code relating to a control within the control’s class, making the code cleaner and easier to understand. For example, you could write a button that handles its own click event — meaning you don’t need to handle the event in your form’s code.

In terms of reusing controls between applications, there are two main ways to do this. The first is to add the control’s source file to every project in which you need the control. Then, when you build the application, the control will be compiled into the main executable. This is the approach you take in this chapter, because it is simpler and will allow you to concentrate on how it works.

The second way is to build a control library. Control libraries are similar to the class libraries that you examined in the previous chapter. In fact, they are class libraries that happen to contain UI-driven classes. Like any other class library, a control library will compile to its own assembly, which you can use in your applications. This method is attractive, because it means you can distribute the assembly to other developers without giving away your source code. You can also make changes to the assembly, and these will be reflected in the applications that use it — even without the applications being recompiled. The techniques for building the controls are the same regardless of whether you are using a control library or using a control only within your application project.

Creating and Testing a User Control

You might find in the applications that you build, that you have a common need for a control that goes to a database to retrieve certain information, such as login information. If you want to build a robust control, you will need to make it as useful as possible to developers using it down the line, while requiring the minimum amount of labor to get it working. You will probably want to encapsulate the functionality of connecting to the database, querying the results, and populating the control with information, so that subsequent developers using your control do not have to know how to do this. This is a key principle of encapsulation — to make life easier for the next developer. In this way, you can also benefit from the more tangible advantage of reducing costs through quality application development and code reuse.

Creating a user control from scratch is not difficult. From one perspective, it is similar to building the Windows forms. In this section, you are going to create a Windows application that uses User Controls. In the first Try It Out, you are going to create a simple control that has three basic button controls inside of it.

When you create your own custom control that uses (hosts) existing controls inside of it, the control is known as an aggregate control.

A different message will be displayed when each button is clicked. You will then see how this control can be used in a standard Windows Forms application.

400

Creating Your Own Custom Controls

Try It Out

Building Your First Control

1.Open Visual Studio 2005 and, on the File menu, select New Project. In the New Project dialog box, select Visual Basic in the Project Types list and Windows Control Library in the Templates list. Enter MyNamespaceControl in the Name field and then click OK.

2.Now click UserControl1.vb in the Solution Explorer and then change the File Name property in the Properties Window to MyNamespace.vb. You will have something that looks very much like a form’s designer without the title bar or borders. Usually, when building a control, you drag on other controls and define a way in which those controls interact. This extra behavior defines a control’s purpose and makes it useful.

3.Drag three Button controls from the Toolbox and drop them on the form and set their Text properties using Figure 13-1 as a guide. Also resize the control so that it also looks similar to Figure 13-1.

Figure 13-1

4.Set the Name properties of the button controls to btnApplicationCopyright, btnScreenBounds, and btnScreenWorkingArea, respectively.

5.At the moment, this control won’t do anything when the buttons are clicked — you need to wire up the event code behind the Click event for each button in order for it to work. Double-click the ApplicationCopyright button and add the highlighted code:

Private Sub btnApplicationCopyright_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnApplicationCopyright.Click

MessageBox.Show(My.Application.Info.Copyright)

End Sub

6.Now select btnScreenBounds in the Class Name combo box at the top of the Code Editor and select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

Private Sub btnScreenBounds_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenBounds.Click

MessageBox.Show(My.Computer.Screen.Bounds.ToString)

End Sub

7.Finally, select btnScreenWorkingArea in the Class Name combo box and select the Click event in the Method Name combo box. Add this code to the Click event handler:

Private Sub btnScreenWorkingArea_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenWorkingArea.Click

MessageBox.Show(My.Computer.Screen.WorkingArea.ToString)

End Sub

401

Chapter 13

8.Now run your project. The user control will be displayed in a TestContainer dialog box as shown in Figure 13-2. From here, you can test your control by clicking each of the buttons and the appropriate information will be displayed in a message box. When you are done, click the Close button.

How It Works

Building the UI for the control is not at all different from building the UI for a Windows application. You simply drag the necessary controls from the Toolbox and drop them on the control designer. Then you wire up the events for the code using the same techniques that you’ve used all along when building Windows applications.

The code that you added for the btnApplicationCopyright button will display the copyright information for your application. This is done by using the My.Application namespace and retrieving the copyright information with the Copyright property of the Info class.

Private Sub btnApplicationCopyright_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnApplicationCopyright.Click

MessageBox.Show(My.Application.Info.Copyright)

End Sub

Figure 13-2

402

Creating Your Own Custom Controls

The code that you added for the btnScreenBounds button will display the current boundaries of the computer screen, which is determined from the screen resolution settings. This is done by using the My.Computer namespace and retrieving the screen boundary information with the Bounds property of the Screen class.

Private Sub btnScreenBounds_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenBounds.Click

MessageBox.Show(My.Computer.Screen.Bounds.ToString)

End Sub

The code that you added for the btnScreenWorkingArea button will display the current working area of the screen. This is the area of the screen that is available to your application’s forms. This is done by using the My.Computer namespace and retrieving the screen working area information with the WorkingArea property of the Screen class.

Private Sub btnScreenWorkingArea_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenWorkingArea.Click

MessageBox.Show(My.Computer.Screen.WorkingArea.ToString)

End Sub

When you built the solution, the control was automatically added to the toolbox in the MyNamespace Control Components tab. This will not become evident, however, until you add a Windows application to this solution. This will allow you to use your user control in your application just as you would with any other control in the toolbox.

To test the control, you can’t just run the project. Instead, you have to put the control onto a form, which will be covered in this next Try It Out.

Try It Out

Adding Your New User Control to a Form

1.Click the File menu and choose Add New Project.

2.In the Add New Project dialog box, ensure that Windows Application is selected in the Templates pane, enter a project name of Controls, and then click OK.

3.Click the MyNamespaceControl Components tab of the Toolbox and drag the MyNamespace control onto Form1.

4.Right-click the Controls project in the Solution Explorer and choose Set as Startup Project from the context menu.

5.Now run your project. The control will appear on the form, and clicking the buttons will have the same effect as they did when you tested the control in the TestContainer dialog box.

How It Works

A custom-built control works the same as any other control that you’ve used up until this point. You simply drag the control from the Toolbox, drop it on your form, and run your project. You didn’t need to wire up any code for the Click events of the buttons, because that functionality is part of the control itself.

403

Chapter 13

Exposing Proper ties from User Controls

A user control is implemented as a class. Therefore, anything that you can do with a class, you can also do with a user control. This means that you can add properties, methods, and events to the user control that can be manipulated by whoever is consuming it. First, take a look at adding a new property to your control.

Your control can have two sorts of properties: those that can be manipulated from the Properties window at design time and those that have to be programmatically manipulated at run time. For example, at design time you might want to change properties pertaining to the color or the font used to draw the control. But at run time you might want to change properties that depend on the contents of a file that the user selected, and so on. Usually, if the property is a fairly simple type such as String, Integer, or Boolean and doesn’t have parameters, it can be manipulated at design time. If the property is a complex object, such as a database or file connection, or if it has parameters, you’ll have to manipulate the property at run time.

Adding Properties

In the next Try It Out, you take a look at adding a property to your control. The property you’re going to add is called ApplicationName. This property will contain the name of your application. When this property is changed, you’ll want to display the text in the title bar of the message boxes on the control.

Try it out

Adding a New Property to the MyNamespace Control

1.To add a new property you need a member variable that will store the value. Switch to the Code Editor for MyNamespace and add the following highlighted code:

Public Class MyNamespace

‘Private members

Private strApplicationName As String = String.Empty

2.When this property is set, you’ll need to set the text in the private member that you just defined. Add this code directly after the lines you added in step 1:

Public Property ApplicationName() As String

Get

Return strApplicationName

End Get

Set(ByVal value As String) strApplicationName = value

End Set End Property

3.To have the message boxes display the application name in the title bar, you need to set the caption parameter of the Show method of the MessageBox class. Modify the Click events for each of the buttons as shown:

Private Sub btnApplicationCopyright_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnApplicationCopyright.Click

MessageBox.Show(My.Application.Info.Copyright, _

strApplicationName)

End Sub

404

Creating Your Own Custom Controls

Private Sub btnScreenBounds_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenBounds.Click

MessageBox.Show(My.Computer.Screen.Bounds.ToString, _

strApplicationName)

End Sub

Private Sub btnScreenWorkingArea_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnScreenWorkingArea.Click

MessageBox.Show(My.Computer.Screen.WorkingArea.ToString, _

strApplicationName)

End Sub

4.To expose the new property for this control to Form1, you need to build the project. Right-click the MyNamespaceControl project in the Solution Explorer and select Build from the context menu. The new property will now be exposed.

5.Switch to the Form Designer for Form1 and select the MyNamespace1 control. In the Properties window the new ApplicationName property will appear under the Misc category (or in the usual place if you have the properties arranged alphabetically).

6.Set the ApplicationName property to My Windows Application.

7.Now run your project and click any of the buttons on the form. Each message box will display the text My Windows Application in the title bar of the message box.

How It Works

You’ll notice that the default value of an empty string for the ApplicationName property has passed through to the designer. If you change the property in the Properties window, the text displayed in the title bar of the message boxes of the control will change.

When the designer needs to update the Properties window, it will call into the object and request the ApplicatioName property. Likewise, when you change the value, it will call into the object and set the property. This also happens when the form is loaded from disk when you start up the designer.

Exposing Methods from User Controls

As you’ve probably guessed, if you can expose new properties for your control, you can also expose new methods. All that you need to do to make this happen is to add a public function or procedure to the control, and then you’ll be able to call it from the form that’s hosting the control, which you do in the next Try It Out.

Try It Out

Adding a Method to the MyNamespace Control

1.Switch to the Code Editor for MyNamespace.vb and add this function:

Public Function TaskBarHeight() As Integer

Return My.Computer.Screen.Bounds.Height - _

My.Computer.Screen.WorkingArea.Height

End Function

405