9.3. Four Additional ObjectsThe Clipboard ObjectThe Clipboard object is used to copy or move information from one location to another. It is maintained by Windows and therefore even can be used to transfer information from one Windows application to another. It is actually a portion of memory that holds information and has no properties or events. If str is a string, then the statement Clipboard.SetText(str) replaces any text currently in the clipboard with the value of str. The statement str = Clipboard.GetText assigns the text in the clipboard to the string variable str. The statement Clipboard.SetText("") deletes the contents of the clipboard. A portion of the text in a text box or combo box can be selected by dragging the mouse across it or by moving the cursor across it while holding down the Shift key. After you select text, you can place it into the clipboard by pressing Ctrl + C. Also, if the cursor is in a text box and you press Ctrl + V, the contents of the clipboard will be inserted at the cursor position. These tasks also can be carried out in code. The SelectedText property of a text box holds the selected string from the text box, and a statement such as Clipboard.SetText(txtBox.SelectedText) copies this selected string into the clipboard. The statement txtBox.SelectedText = Clipboard.GetText() replaces the selected portion of txtBox with the contents of the clipboard. If nothing has been selected, the statement inserts the contents of the clipboard into txtBox at the cursor position. The clipboard can actually hold any type of data, including graphics. Any time you use the Copy menu item, you are putting information into the clipboard. The Paste menu item sends that data to your program. The Random ClassVisualBasic has a useful object called a random number generator that is declared with a statement of the form Dim randomNum As New Random If m and n are whole numbers, with m<n then the value of randomNum.Next(m, n) is a randomly selected whole number from m through n, including m but excluding n. The Next method of this built-in object allows us to produce some interesting applications. Example 1.
The MenuStrip ControlVisual Basic forms can have menu bars similar to those in most Windows applications. Figure 9.11 shows a typical menu, with the Order menu revealed. Here, the menu bar contains two menu items (Order and Color), referred to as top-level menu items. When the Order menu item is clicked, a dropdown list containing two second-level menu items (Ascending and Descending) appears. Although not visible here, the dropdown list under Color contains the two second-level menu items Foreground and Background. Each menu item is treated as a distinct control that responds to a click event. The click event is triggered not only by the click of the mouse button, but also for top-level items by pressing Alt + accesskey and for second-level items by just pressing the access key. The event procedure for the Ascending or Descending menu item also can be triggered by pressing the shortcut key combination Ctrl + A or Ctrl + D. Figure 9.11. A simple menu.
Menus are created with the MenuStrip control, which is usually the third control in the Menus & Toolbars section of the Toolbox. Each menu item has a Text property (what the user sees) and a Name property (used to refer to the item in the code.) The following steps are used to create the Order-Color menu:
Example 2. |
The following program uses the menu just created to alter the colors of a list box and the order of its items. The form has the text "Demonstrate Menus" in its title bar. Private Sub frmDemo_Load(...) Handles MyBase.Load lstOutput.Items.Add("makes") lstOutput.Items.Add("haste") lstOutput.Items.Add("waste") End Sub Private Sub mnuOrderAsc_Click(...) Handles mnuOrderAsc.Click lstOutput.Sorted = True End Sub Private Sub mnuOrderDesc_Click(...) Handles mnuOrderDesc.Click 'This code uses the fact that if a list is in ascending order, 'then reading it backwards gives a descending list Dim temp(2) As String 'Hold ascending array of items lstOutput.Sorted = True 'Sort the items alphabetically For i As Integer = 0 To 2 'Place sorted items into the array temp(i) = CStr(lstOutput.Items(i)) Next lstOutput.Sorted = False 'Turn off the Sorted property lstOutput.Items.Clear() For i As Integer = 2 To 0 Step -1 lstOutput.Items.Add(temp(i)) Next End Sub Private Sub mnuColorForeRed_Click(...) Handles mnuColorForeRed.Click lstOutput.ForeColor = Color.Red End Sub Private Sub mnuColorForeBlue_Click(...) Handles mnuColorForeBlue.Click lstOutput.ForeColor = Color.Blue End Sub Private Sub mnuColorBackYellow_Click(...) Handles_ mnuColorBackYellow.Click 'Make Yellow the background color of the list box, guarantee that a 'check mark appears in front of the menu item Yellow and not in front 'of the White menu item lstOutput.BackColor = Color.Yellow mnuColorBackYellow.Checked = True mnuColorBackWhite.Checked = False End Sub [Run, click on the Ascending item in the Order menu, click on the Color menu item, hover over the Foreground item, and click on Red.]
|
A Visual Basic program can contain more than one form. Additional forms are created from the Project menu with Add Windows Form (Alt/P/F), which brings up an Add New Item dialog box. See Figure 9.13. To add the new form select Windows Form from the Installed Templates pane, optionally type in a name, and press the Add button. The second form has default name Form2.
The name of each form appears in the Solution Explorer window (see Figure 9.14), and either form can be made the active form by double-clicking on its name. (When a form is active, its Form designer and Code window are displayed in the Main area.) Also, the names of both forms appear on tabs in the Main area.
The most common use of a second form is as a customized dialog box that is displayed to present a special message or request specific information. When a Message or Input dialog box appears, the user cannot shift the focus to another form without first closing the dialog box by clicking on OK or Cancel. If a form is displayed with the ShowDialog method, then the form will exhibit this same behavior. The user will not be allowed to shift the focus back to the first form until the second form disappears. Such a form is said to be modal. It is customary to set the FormBorderStyle property of modal forms to Fixed Dialog. When a program is run, the first form created is the only one visible. After that, the second form will appear when the ShowDialog method is executed and disappear when its Close method is invoked.
Form2 is actually a template for a form in the same manner that the TextBox class denoted by the TextBox icon on the ToolBar is a template for the actual text boxes appearing on a form. A text box on a form is said to be an instance of the TextBox class. An instance of Form2 is created with a statement such as
Dim secondForm As New Form2()
which also provides a variable, secondForm, that will be used to refer to the instance of the form.
Variables declared with Dim statements are either local (visible only to the procedure where they are declared) or class-level (visible to the entire form where they were declared). If a variable is declared in the Declarations section of Form2 with the word "Dim" replaced with "Public," then the value of the variable will be available to all forms in the program. However, when a Public variable is used in Form1, it is referred to by an expression such as secondForm.variableName. (As a personal analogy, at home you might be called John, but to strangers you might be introduced as "Fred's son John" to distinguish you from anyone else named John.)
The following program uses a second form as a dialog box to total the different sources of income. Initially, only frmIncome is visible. The user types in his or her name and then either can type in the income or click on the button for assistance in totaling the different sources of income. Clicking on the button from frmIncome causes frmSources to appear and be active. The user fills in the three text boxes and then clicks on the button to have the amounts totaled and displayed in the Total Income text box of frmIncome.
'frmIncome's code Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim secondForm As New frmSources() 'Instantiate the second form secondForm.ShowDialog() 'Show second form and wait until it closes. 'Then execute rest of the code in this procedure. txtTotIncome.Text = FormatCurrency(secondForm.sum) End Sub 'frmSources's code Public sum As Double 'Holds the sum of the text boxes' values 'The keyword Public makes the variable sum available to frmIncome. Private Sub btnCompute_Click(...) Handles btnCompute.Click 'Store the total into the Public variable sum sum = CDbl(txtWages.Text) + CDbl(txtIntIncome.Text) _ + CDbl(txtDivIncome.Text) Me.Close() 'Close the form as it is not needed anymore End Sub [Run, enter name, click the button, and fill in the sources of income.] Note: After the Compute Total Income button is pressed, frmSources will disappear and the sum of the three numbers will be displayed in the Total Income text box of frmIncome.
|
Note: If a Structure is defined in frmIncome, it can be used as a data type in frmSources. However, in frmSources it must be referred to as frmIncome. structureName.
Q1: | What is the effect of the following event procedure? Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim randomNum As New Random Dim contestant() As String = {"Mary", "Pat", "Linda", _ "Barbara", "Maria"} Dim number As Integer, temp As String For i As Integer = 0 To 4 number = randomNum.Next(i, 5) temp = contestant(i) contestant(i) = contestant(number) contestant(number) = temp Next lstOutput.Items.Clear() For i As Integer = 0 To 4 lstOutput.Items.Add(contestant(i)) Next End Sub |
In Exercises 1 through 18, describe the effect of executing the statement(s).
1. | Clipboard.SetText("") |
2. | Clipboard.SetText("Hello") |
3. | Clipboard.SetText(txtBox.SelectedText) |
4. | txtBox.SelectedText = Clipboard.GetText() |
5. | txtBox.Text = Clipboard.GetText |
6. |
Dim strVar As String = "Happy" Clipboard.SetText(strVar) |
7. |
Dim strVar As String strVar = Clipboard.GetText |
8. |
Dim randomNum As New Random txtBox.Text = CStr(randomNum.Next(1, 10)) |
9. |
Dim randomNum As New Random Dim number As Integer 'Assume the array Pres() contains the names of the 43 U.S. Presidents number = randomNum.Next(0, 43) txtBox.Text = Pres(number) |
10. |
Dim randomNum As New Random '95 characters can be produced by the computer keyboard txtBox.Text = Chr(randomNum.Next(32, 127)) |
11. |
Dim randomNum As New Random Dim number As Integer, temp As String 'Suppose the array states() contains the names of the 50 states number = randomNum.Next(0, 50) lstBox.Items.Add(states(number)) temp = states(number) states(number) = states(49) states(49) = temp lstBox.Items.Add(states(randomNum.Next(0, 49))) |
12. |
Dim randomNum As New Random Dim suit() As String = {"Hearts", "Clubs", "Diamonds", "Spades"} Dim denomination() As String = {"2", "3", "4", "5", "6", _ "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"} txtBox.Text = denomination(randomNum.Next(0, 13)) & " of " & _ suit(randomNum.Next(0, 4)) |
13. | mnuOrderAsc.Checked = True |
14. | mnuOrderAsc.Checked = False |
15. | mnuOrderAsc.Text = "Increasing Order" |
16. | Me.Close() |
17. | Public address As String 'In Declarations section of Form2 |
18. |
Dim secondForm As New Form2() secondForm.ShowDialog() |
In Exercises 19 through 34, write one or more lines of code to carry out the task.
19. | Replace the selected portion of txtBox with the contents of the clipboard. |
20. | Clear out the contents of the clipboard. |
21. | Place the word "Rosebud" into the clipboard. |
22. | Copy the selected text in txtBox into the clipboard. |
23. | Delete the selected portion of txtBox. |
24. | Assign the contents of the clipboard to the Integer variable amount. |
25. | Display in txtBox a randomly selected number from 1 to 100. |
26. | Twenty names are contained in the array Names(). Display a randomly selected name in txtBox. |
27. | Display in txtBox a letter randomly selected from the alphabet. |
28. | The file CITIES.TXT contains the names of fifty cities. Display a randomly selected city in txtBox. |
29. | Display in txtBox the sum of the faces after tossing a pair of dice. |
30. | Twenty names are contained in the array Rivers(). Randomly select two different names from the array and display them in lstBox. |
31. | Remove the check mark in front of the menu item named mnuOrderDesc. |
32. | Change the text for mnuOrderDesc to "Decreasing Order". |
33. | Close the form containing the line of code. |
34. | Declare the Double variable number so that its value will be available to other forms. |
Exercises 35 and 36 refer to Example 2.
35. | Conjecture on the effect of the statement mnuOrderAsc.Enabled = False and test your conjecture. |
36. | Conjecture on the effect of the statement mnuOrderAsc.Visible = False and test your conjecture. |
37. | Write a program with a single text box and a menu with the single top-level item Edit and the four second-level items Copy, Paste, Cut, and Exit. Copy should place a copy of the selected portion of txtBox into the clipboard, Paste should duplicate the contents of the clipboard at the cursor position, Cut should delete a selected portion of the text box and place it in the clipboard, and Exit should terminate the program. |
38. | The file MEMBERS.TXT contains the names of the 100 members of a club. Write a program to randomly select people to serve as President, Treasurer, and Secretary. Note: A person cannot hold more than one office. |
39. | Place the names of the 52 playing cards into the array deckOfCards(). Then display the names of five randomly chosen cards in lstPokerHand. |
40. | Write a program that repeatedly "throws" a pair of dice and tallies the number of tosses and the number of those tosses that total seven. The program should stop when 100 sevens have been tossed. The program should then report the approximate odds of tossing a seven. (The approximate odds will be "1 in" followed by the result of dividing the number of tosses by the number of tosses that came up seven.) |
41. | Write a program using the form in Figure 9.15 Each time the button is pressed, a Random object is used to simulate a coin toss and the values are updated. The figure shows the status after the button has been pressed 537 times. Figure 9.15. Sample run of Exercise 41.
Note: You can produce tosses quickly by just holding down the Enter key. Although the percentage of heads initially will fluctuate considerably, it should stay close to 50% after many (say, 1000) tosses. |
42. | Write a program containing the two forms shown in Figure 9.16 Initially, the Number to Dial form appears. When the Show Push Buttons button is clicked, the Push Button form appears. The user enters a number by clicking on successive push buttons and then clicks on Enter to have the number transferred to the read-only text box at the bottom of the first form. Figure 9.16. Sample run of Exercise 42. |
43. | Write a program to randomly select 40 different people from a group of 100 people whose names are contained in a text file. |
44. | The Birthday Problem. Given a random group of 23 people, how likely is it that two people have the same birthday? To answer this question, write a program that creates an array of 23 elements, randomly assigns to each subscripted variable one of the integers from 1 through 365, and checks to see if any of the subscripted variables have the same value. (Make the simplifying assumption that no birthdays occur on February 29.) Now expand the program to repeat the process 100 times and determine the percentage of the time that there is a match. |
A1: | The event procedure places the names of the contestants in a randomly ordered list. |