Working with a Common Event Handler
As you saw in the preceding example, one benefit of control arrays is the ability to have a common event handler. This section features a program that allows users to input some numbers into a numeric telephone touch pad to place a call. Users also can set whether the call should be made by pulse or tone and can choose to send a fax or a simple voice call.
Don't worry if you don't know anything about telephony programming--you won't be writing any. This example is simply designed to show how control arrays could be used in this application.
This program uses a control array of CommandButtons to handle user input. Each keypad button is part of the cmdNum control array. Using a control array greatly simplifies matters. In this project, if you didn't use a control array, you would have 12 event procedures to program--not a very pleasant undertaking. However, when you use a control array, you have only one event procedure to program. You use the Index argument within the control array's one event procedure to figure out which control fired the event procedure.
LISTING 3.19 Keypad Event Handler
01 Private Sub cmdNum_Click(Index As Integer)
02 Dim strChar As String
03
04 `Find out which button was clicked by analyzing
05 the Index argument. Depending on which button
06 `you push, set the other string variable accordingly.
07 Select Case Index
08 `This button has the "*" character
09 Case 10
10 strChar = "*"
11 `This button has the "#" character
12 Case 11
13 strChar = "#"
14 `All the buttons have captions that match
15 `their index value.
16 Case Else
17 strChar = CStr(Index)
18 End Select
19
20 ` Add the new digit to the phone number.
21 lblNumber.Caption = lblNumber.Caption & strChar
22
23 End Sub
The only issue with this code is that each CommandButton's Index property must match exactly with its Caption property. For instance, this code assumes that the button marked as the one digit has a control array index of 1, the two button has an index of 2, and so on. If these buttons were deleted and re-created, they would have to be put back in order exactly or the code wouldn't work.
Listing 3.20 shows a revised version of this code, which still uses a single event handler but doesn't rely on the value of Index. Instead, it simply uses the value of the Caption property. It's also quite a bit shorter and more reliable.
LISTING 3.20 Revised Keypad Event Handler
01 Private Sub cmdNum_Click(Index As Integer)
02 lblNumber.Caption = lblNumber.Caption _
& cmdNum(Index).Caption
03 End Sub
Saturday, December 26, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment