Enhancing a Windows Control

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 16.  Creating Your Own Windows Controls


The example you worked through earlier in this chapter introduced the concepts involved in creating a custom Windows control by combining existing controls into a single object. However, you can also create "new" controls simply by adding capabilities to an existing control. This means that you are working with a single base control but adding properties, methods, and events to provide additional capabilities to the user. For example, you might want to create a special scrollbar control that uses letters instead of numbers or a text box that accepts only certain characters.

Placing the code that performs these tasks into a separate Windows control makes it easier to use the code in future programs. For example, rather than add special code to every TextBox control in your program, you can simply use your "enhanced" control in place of the text box. To create these enhanced controls, you use many of the same techniques that you learned in the previous sections:

  1. Start a new Windows Control Library project.

  2. Add the base control to the UserControl window.

  3. Add code for properties, methods, and events.

The following sections walk you through these steps, using a text box as the base control. Your "enhanced" text box will be known as a "Limited Character Text Box." It will have a user-defined property that allows the programmer to choose a set of acceptable characters that the user can enter. This additional property, CharAccept, will allow the user to restrict text entry to only letters, only numbers, or allow both.

The complete EnhancedTextBox sample project that you will create in this section, parts of which are excerpted in code listings, is available for download from www.quepublishing.com. Look for the file named EnhTextBox.zip.

Setting Up the Base Control

The steps for creating the enhanced TextBox control are similar to the steps you used to create the NameText control. For the enhanced TextBox control, the steps are as follows:

  1. Start a new Windows Control Library project named EnhancedTextBox .

  2. Change the control's FileName property from UserControl1.vb to EnhTextBox.vb.

  3. Click the Designer window to display the design-time properties for the control. Change its Name property to EnhTextBox .

  4. Add a TextBox control to the Designer window. Set its Location property to 0, 0(the upper-left corner), and its Size property to 100, 20.

  5. Set the TextBox control's AutoSize property to False. This will allow your code to dynamically resize both the height and width of the TextBox control as the user resizes the EnhTextBox control.

  6. Name the text box txtCharSet, and clear its Text property.

  7. Click a blank area of the Designer window to select the EnhTextBox control, then set its Size property to match the size of the txtCharSet text box it contains (100, 20).

    After you set up the user interface of the enhanced text control, it should look like the one in Figure 16.15.

    Figure 16.15. The base control, pictured here, will be enhanced with additional capabilities.

    graphics/16fig15.gif

  8. Right-click the Designer window, then choose View Code from the pop-up menu.

  9. Choose (Base Class Events)in the Code window's Class Name box, then choose Resize in the Method Name box to display the control's Resize event handler.

  10. Add the following lines of code to the procedure:

     txtCharSet.Height = Me.Height  txtCharSet.Width = Me.Width 

    This simple two-line Resize event handler is all the code necessary for the user interface of the sample control. Its purpose is to keep the text box the same size as the UserControl object.

  11. Save your project.

Before moving on, test the Resize event handler by performing the following steps:

  1. Right-click the EnhancedTextBox project in the Solution Explorer window, then choose Build from the pop-up menu. This compiles the project's DLL.

  2. Close the object's Code and Designer windows.

  3. Choose File, Add Project, New Project; select the Windows Application template and give it any name you want.

  4. Draw an instance of the EnhancedTextBox control on Form1.vb, and try resizing it. Notice that as you resize the EnhancedTextBox control, the constituent text box resizes itself.

Note

When you are developing a custom control, the code you write is used at design time in the host program. In other words, the client control's runtime is the host project's design time.


Now, it is time to work on enhancing the control. Close the test project's Form1.vb for now.

Enhancing the Base Control

The enhancement you are going to make to the txtCharSet TextBox control that comprises the EnhancedTextBox control is to tell it whether it should accept just letters, just numbers, or any characters as input. You can do so by adding your own property, called CharAccept, which can have one of the following three values:

  • 0 Accepts any character

  • 1 Accepts only numeric characters

  • 2 Accepts only alpha characters

Declaring the CharAccept Property

To declare the CharAccept property, you need to add a private variable to store the property value internally. We will call this private variable mCharAccept (m- is often used as a naming convention prefix to denote memory variables that are used internally in a class). The code that we write for the control will examine the value of this private variable and act according to its value.

To declare the private variable, open the Code window for EnhTextBox.vb and enter the following line of code below the "Windows Form Designer Generated Code" designator:

 Private mCharAccept As Integer 
Defining Property Values

As mentioned earlier, the CharAccept property will be designed to accept three possible values 0, 1, and 2. To make the control easier to use by developers, it would be nice to have mnemonic values predefined for the three values, giving the user (developer) an easy way of remembering the purpose of each value. To accomplish this, we first need to set up an enumeration, or a predefined list of values that together represent a custom type. For example, when you add a TextBox control to a form and select the TextAlign property in the Properties window, you can use a drop-down box to choose from three possible predefined property values Left, Right, or Center.

We will create an enumeration to contain mnemonic representations of the three possible CharAccept values. The mnemonics that we will use for the three values will be AnyCharacter, NumericOnly, and AlphaOnly, representing the three values 0, 1, and 2, respectively.

To create the enumeration, enter the following code into the Code window for the EnhTextBox control. A good place would be just after the Private mCharAccept As Integer declaration you placed just below the "Windows Form Designer Generated Code" section:

 Public Enum EnhTextBoxConstants      AnyCharacter = 0      NumericOnly = 1      AlphaOnly = 2  End Enum 

The name you gave to the enumeration, EnhTextBoxConstants, will be used when coding the property.

Coding the CharAccept Property

Next, you need to write the code for the new CharAccept property and expose it to users of your control. You will do so by coding a Property procedure, as discussed earlier in this chapter. In this case, the Property procedure will need to be read/write; that is, your control's users should be able to both read (Get) and assign (Set) the value of the CharAccept property. The code for the CharAccept property is fairly easy to understand. When the host application needs to read the value of the CharAccept property, the Get portion of the Property procedure simply passes what is stored in the mCharAccept private variable. When the value of the CharAccept property is modified by the host application, the Let portion of the Property procedure assigns one of the valid values to the private variable.

Begin coding the Property procedure by typing the procedure's declaration, Property CharAccept() As EnhTextBoxConstants, just above the End Class statement at the bottom of EnhTextBox's Code window. When you press Enter after typing that line of code, the shell of the complete Property procedure is filled in for you. Note that we are using the enumeration we created as the declared type of the property. The user can set the property to one of the three values defined in the enumeration.

Listing 16.3 shows the code for the complete Property CharAccept procedure, including comments:

Listing 16.3 EnhTextBox.zip Creating the CharAccept Property
 Property CharAccept() As EnhTextBoxConstants      Get          'Set the property to the current value of          ' the private mCharAccept variable.          CharAccept = mCharAccept      End Get      Set(ByVal Value As EnhTextBoxConstants)          Select Case Value              Case 1, 2                  'If the user has set the property to 1 or 2,                  ' use that as the new value of the private                  ' mCharAccept variable.                  mCharAccept = Value              Case Else                  'If the user has entered                  mCharAccept = 0          End Select      End Set  End Property 

Note

If you ever worked with custom controls in previous versions of Visual Basic, you may recall having to write cumbersome code for the PropertyBag object and the PropertyChanged, ReadProperties, and WriteProperties events, allowing custom controls to retain the values of their properties between instances. Thankfully, properties for custom controls in Visual Basic .NET are inherently persistent; that is, they retain their values without any explicit work on the part of your program.


Preparing to Raise an Event

If the user enters an invalid character into the text box (based on the setting of the CharAccept property), you may want to let the host application know of this occurrence in addition to not accepting the character. You can do so by raising an event when invalid input is received; developers using your control can choose to react to the event or ignore it.

To have a control raise a custom event, you must first declare the event. This lets the control know that you may possibly be raising that event. You will see how to raise the event in the next section. To declare the event, add the following line of code below the section, near the mCharAccept declaration you added earlier:

 Public Event BadKeyEntered() 

To raise the event, you simply use the RaiseEvent statement at the appropriate place(s) in the control's code. When your control raises the event, it works just like any other event as far as the host application is concerned. Your control's user can write code in the host program's controlname_BadKeyEntered event handler to respond to the occurrence of a BadKeyEntered event.

Writing Code to Change the Text Box's Behavior

Now that you have defined a custom property for the control and declared the existence of a potential event, the next step in this sample project is to create the code that utilizes the value of the CharAccept property to make the limited character text box do something different from a normal text box. In this case, you can use the text box's KeyPress event to scan each character as it is entered by the end user.

Each time the KeyPress event occurs (that is, each time the user presses a key while the txtCharSet control has the focus) Visual Basic .NET will invoke the KeyPress event handler, passing an argument named e, whose type is System.Windows.Forms.KeyPressEventArgs. Arguments of this type support a KeyChar property, which contains the keyboard character matching the key that the user has pressed.

The KeyPress event handler will determine the equivalent ASCII code value of the key that the user pressed, which will make it easier to determine whether the character is within the acceptable range (based on the CharAccept property). This ASCII code will be stored in a variable named KeyASCII (which VB6 users may recognize as the name of a similar argument passed to the KeyPress procedure in previous versions).

Because three possible values of the CharAccept property need to be handled, you can use a Select statement to handle the choices. If CharAccept is set to 0(AnyCharacter), then the user's input is accepted and the procedure is exited. If, however, CharAccept is set to one of the other two possible values, the user's input is examined for validity. If he enters a valid character, the procedure is exited and processing continues normally. When an invalid character is entered, the Handled property of the e argument is set to True (which instructs the program that the key press has been handled and can be ignored); the BadKeyEntered event is raised, and the Beep function is called to give the user audio feedback that the character he typed was rejected.

Here's one other item of note: You need to allow the use of the Backspace key (ASCII character 8) in any of the character sets that you use. Otherwise, the user cannot delete the previous character. The code for the complete KeyPress event handler is shown in Listing 16.4, with comments to help you follow the logic.

Listing 16.4 EnhTextBox.zip Coding the Text Box's Enhanced Behavior
 Private Sub txtCharSet_KeyPress(ByVal sender As Object, _      ByVal e As System.Windows.Forms.KeyPressEventArgs) _      Handles txtCharSet.KeyPress      Dim KeyASCII As Short      'Convert the KeyChar argument to an ASCII value      KeyASCII = Asc(e.KeyChar)      'If the user pressed Backspace, it's OK      If KeyASCII = 8 Then Exit Sub      'Decide what to do base on the CharAccept property      Select Case mCharAccept          Case 0 'Any character is acceptable              Exit Sub          Case 1 'Only numbers may be entered              If KeyASCII >= 48 And KeyASCII <= 57 Then                  Exit Sub              Else                  e.Handled = True                  RaiseEvent BadKeyEntered()                  Beep()              End If          Case 2 'Only letters may be entered              If KeyASCII >= 65 And KeyASCII <= 90 Then                  Exit Sub              ElseIf KeyASCII >= 97 And KeyASCII <= 122 Then                  Exit Sub              Else                  e.Handled = True                  RaiseEvent BadKeyEntered()                  Beep()              End If      End Select  End Sub 

Testing the Enhanced Text Box

After you enter all the code for the control, you can test the EnhTextBox control by following these steps:

  1. Save your project.

  2. You probably still have a test Windows Application project as part of the current solution; if not, add one.

  3. Close the Designer and Code windows for the EnhTextBox control.

  4. Rebuild the EnhTextBox control by right-clicking it in the Solution Explorer and choosing Build.

  5. Open the Designer window for your test project. Delete any existing previous instances of the EnhTextBox control and add a new one.

  6. Right-click the EnhTextBox control, then choose View Code. Notice that you can create a BadKeyEntered event handler for the control. Add the following line of code to the EnhTextBox1_BadKeyEntered event handler:

     MsgBox("You pressed a bad key!") 

  7. Run the test program and try out the control. Try setting the CharAccept property to different values to verify that it accepts only the keystrokes you want, and that the BadKeyEntered event is invoked when you enter an invalid character.

If you have problems with the control, you can use the same debugging techniques to find the problems in a control as you do to find problems in standard programs. You can set breakpoints and step through the code line by line, whether in the EnhTextBox control project or in the Windows Application project. (See Chapter 7, "Controlling the Flow of Your Program," for more information on debugging your code.)

For more information on locating errors in your programs, p. 717


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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