Professional Documents
Culture Documents
(Contd .)
Using the Command Button tool in the Visual Basic toolbox, add a new command button to the main form in our program. In the Properties window, change the Name property of this button from Command1 to Command in preparation for setting up a control array, and clear its Caption property so the button appears blank.
(Cont)
(Cont )
Next, add a second button to the form, and set its Name property to Command as well. When you do, Visual Basic opens a dialog box that states: You already have a control named Command. Do you want to set up a control array? Click Yes to create a control array, which means we will be able to refer to our controls using an index instead of simply by name. Add a total of nine buttons to the main form in our program, arranged in a 33 grid similar to a standard tictac-toe game, give each of the buttons the name Command, and clear their captions. That completes the preliminary design now were ready to write some code.
(Contd )
(Contd )
(Contd..)
Visual Basic programs like this one are centered around events, and most events occur when the user triggers them. In this case, a Click event is triggered when the user clicks a button, and were passed the buttons index in the control array of buttons as the Index parameter in Command_Click()
(Contd..)
When the user clicks a button, we need to know which character to display, and we ll keep track of that in a form-wide variable named xNow; if xNow is True, we should display an x, if False, an o. To add that form-wide variable, click the (General) entry in the left drop-down list box in the code window, and add this code to the general section of our form:
Dim xNow
You can indicate the type of a variable when declaring it with Dimto indicate that xNow is a Boolean variable, we could declare it this way:
Dim xNow As Boolean
(Contd..)
We need to initialize that form-wide variable, xNow, and we do that when the form first loads in the Form_Load() procedure, which is run when the form is first loaded. Open that procedure now by selecting the Form item in the code windows left drop-down list box, or by double-clicking the form itself; here, we just initialize xNow to True:
Private Sub Form_Load() xNow = True End Sub
(Contd..)
Now we will toggle the clicked buttons caption depending on the current setting of xNow. To reach the clicked button in Command_Click(), we use the control array index passed to us this way: Private Sub Command_Click(Index As Integer) If xNow Then Command(Index).Caption = "x" Else Command(Index).Caption = "o" End If ... End Sub Finally, we toggle xNow (from True to False or False to True) this way: Private Sub Command_Click(Index As Integer) If xNow Then Command(Index).Caption = "x" Else Command(Index).Caption = "o" End If xNow = Not xNow End Sub
2 4 4 4