Creating a Custom Control

Creating a Custom Control

With Visual Basic .NET, you have the ability to create custom, managed controls. If you've ever built ActiveX controls in Visual Basic 6, you already know how to accomplish this. I'll briefly touch on the highlights of control construction by illustrating how to build a simple control that raises an event in the host.

Changing the Background Color of a Text Box

As you know, a control cannot exist on its own but instead needs a host container such as a form to exist. In this example, we'll create a control that contains a context menu and permits the user to change the control's background color. The example is admittedly simple and contrived, but all of the main points are illustrated. A sample of our control is shown in Figure 14-7.

Figure 14-7

This control permits the user to change the control's background color.

When Change Color is selected, a common dialog box is displayed with all the colors available on that computer. The user can select a color to change the text box's background color property. The common dialog is contained in the custom control. The Windows Forms ColorDialog control is a preconfigured dialog box that allows the user to select a color from a palette and add custom colors to that palette. It is the same dialog box that you see in other Windows applications, such as the Display control panel. We will use the common dialog box within our control in lieu of configuring our own dialog box.

When the color is changed in our custom control, the control fires an event in the host container. The program displays a message box, shown in Figure 14-8, that indicates the new color. Simple, but this example illustrates how events can be fired in the host. In addition, parameter values such as the color the text box was changed to can also be passed back to the host quite easily.

Figure 14-8

A message box is displayed when the control fires an event.

Building Our Control

Start a new project, but this time select a Windows Control Library project. Name the new project Custom Text Control. When a Windows Control Library project is started, a user control designer window is added to the IDE, which looks much like a form but is actually the substrate on which we will build our control. You can see the control designer in Figure 14-9.

Figure 14-9

A blank control designer.

Add a text box to the user control, set its Text property to an empty string, and resize the substrate to the size shown in Figure 14-10. (Make the control substrate as small as possible.) When we draw our control on the host form, the substrate and any controls on that substrate are included. Using the toolbox, add a ColorDialog control to the control.

Figure 14-10

Resize the substrate and add a ColorDialog control.

Adding Code to Our Control

We want to add two class-scoped items to our control. The first is a variable, cPreviousColor, that will hold the color of the text box before the user changes the color. With this variable, we can add an undo feature so that if the user makes a terrible mistake, he or she can simply reset the color to its previous value. The other item is an event procedure declaration, colorChanged, that will be visible in any host that uses our control. We will pass in the value of the new text box background color as a parameter to this event. Later in the code, we will raise this event when certain conditions are met.

Public Class UserControl1 Inherits System.Windows.Forms.UserControl Dim cPreviousColor As System.Drawing.Color Public Event colorChanged( _ ByVal color As System.Drawing.Color)

Once these items are defined, the next job is to call a procedure that sets up our text box's context menu. This procedure is called immediately after the control sites and initializes any of its own controls.

Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() setUpContextMenu()End Sub

Add the setUpContextMenu procedure as well as the two routines that handle the Click event for each of the menu items. Here's the code:

Sub setUpContextMenu() Dim cmContextMenu As New ContextMenu() Dim mnuItem1 As New MenuItem("Change Color") Dim mnuItem2 As New MenuItem("Restore Previous") With cmContextMenu .MenuItems.Add(mnuItem1) .MenuItems.Add(mnuItem2) End With TextBox1.ContextMenu = cmContextMenu AddHandler mnuItem1.Click, AddressOf menuItem1Click AddHandler mnuItem2.Click, AddressOf menuItem2Click End Sub Sub menuItem1Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) With ColorDialog1 .AllowFullOpen = True .AnyColor = True .SolidColorOnly = False .ShowHelp = True .Color = TextBox1.BackColor cPreviousColor = .Color .ShowDialog() TextBox1.BackColor = .Color RaiseEvent colorChanged(.Color) End With End Sub Sub menuItem2Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) TextBox1.BackColor = cPreviousColor End Sub

Build the project before you continue.

Adding Our Custom Control to the Host Form

We need to add another project to our solution, so select File | Add Project | New Project to display the Add New Project dialog box. Select a Windows Application project, and name it Host.

Now open the toolbox and scroll to the bottom of the Windows Forms tab. You'll see that a UserControl is now on the list. Drag this control to the Host form as you would any other control. If you look closely at the control on the form, you can see the substrate boundaries, as shown in Figure 14-11.

Figure 14-11

Add the custom control to the form.

Now look at the Solution Explorer. You'll see that Visual Basic .NET automatically adds a reference to the control, as shown in Figure 14-12.

We only need to add a single line of code to the host. The message box alerts us to the fact that the control raised the colorChanged event. And because we passed in the value of the new color, we will show that as well.

Figure 14-12

Visual Basic .NET automatically adds a reference to the control.

Private Sub UserControl11_colorChanged(ByVal color As _ System.Drawing.Color) Handles UserControl11.colorChanged MessageBox.Show("The textbox color was changed to " _ & color.ToString, "Custom Control", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) End Sub

The last step that's required is to set the host form as the project's start-up object. Bring up the Solution Explorer, select the Host project, right-click, and select Set As Startup Project. Now press F5 and run the new control in its host form.

How It Works

I'll cover context menus and event handlers in more detail in our next project, but suffice it to say that in this project we first dimension a context menu, create two new menu items (using the overloaded constructor that permits us to add the text when we build them), and then add each menu item to the MenuItems collection of the context menu.

Sub setUpContextMenu() Dim cmContextMenu As New ContextMenu() Dim mnuItem1 As New MenuItem("Change Color") Dim mnuItem2 As New MenuItem("Restore Previous") With cmContextMenu .MenuItems.Add(mnuItem1) .MenuItems.Add(mnuItem2) End With

After the context menu is built, it's added to the text box's ContextMenu property. Of course, the menu items can't do anything until we build event handlers for them. When the Click event is fired, the respective delegate for menu item one or two will be fired. Again, we will cover this a bit more in the next project.

 TextBox1.ContextMenu = cmContextMenu AddHandler mnuItem1.Click, AddressOf menuItem1Click AddHandler mnuItem2.Click, AddressOf menuItem2Click End Sub

When the user clicks the Change Color menu item, the handler refers the code to the menuItem1Click delegate to handle it. Before we display the Color dialog box we want to first set the Color property to the current background color of the text box. We do this so that if the user cancels the Color dialog box without selecting a color, the new color will be the same as the current color. The ShowDialog method displays the Color dialog box. Because this dialog box is displayed modally, control won't be returned to our code until the user dismisses the dialog. When that happens, the background color of the text box is set to either a new color or the existing color, if the operation is canceled.

The next item of interest is the RaiseEvent command, which fires the event we declared at the top of the control class. This event in turn fires the event in the host and passes in the Color value as a parameter.

Sub menuItem1Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) With ColorDialog1 .AllowFullOpen = True .AnyColor = True .SolidColorOnly = False .ShowHelp = True .Color = TextBox1.BackColor cPreviousColor = .Color .ShowDialog() TextBox1.BackColor = .Color RaiseEvent colorChanged(.Color) End With End Sub

If the user clicks Restore Previous, we set the background color of the text box to the value stored in cPreviousColor.

Sub menuItem2Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) TextBox1.BackColor = cPreviousColor End Sub

This code has been kept to a minimum so that I could illustrate the important points of control construction. As you see, you already know how to write a control because the methodology is almost the same as for a standard Windows form. What's important to keep in mind is that you are working with a different audience when developing controls. The audience for your control is not a user but a programmer. The goal is to make your controls as general as possible, and providing many events and properties in your controls accomplishes this. A programmer can respond to whichever events are appropriate for the task at hand and ignore the rest.



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net