' Ch. 9 Demo 4
' Mr. Minich
' Purpose - using a second VB form and appending to a sequential access file
Option Explicit
Dim mintScore As Integer ' user's score
Private Sub Form_Load()
' opens files and displays first question
Dim strFirstQuestion As String ' first question
Open "Z:\Basic\Ch 9\Ch9Demo4\ch9demo4data.txt" For Input As #1
Input #1, strFirstQuestion ' reading & displaying first question
lblQuestion.Caption = strFirstQuestion
cmdDisplay.Visible = False
End Sub
Private Sub cmdNext_Click()
Dim strQuestion As String ' next question
Dim strAnswer As String ' answer to next question
Dim intPreviousHighScore As Integer ' previous high score
Dim strName As String ' player's name
Dim frmForm As Form
If (cmdNext.Caption = "&Enter") Then
Input #1, strAnswer
If (strAnswer = txtUserAnswer.Text) Then
mintScore = mintScore + 1 ' adding point if answered correctly
End If
If (Not(EOF(1))) Then ' displaying next question if not past end of file
Input #1, strQuestion
lblQuestion.Caption = strQuestion
txtUserAnswer.SetFocus
Else ' close file otherwise
lblQuestion.Caption = "You scored " & mintScore & " points."
txtUserAnswer.Visible = False
cmdNext.Caption = "E&xit"
cmdNext.SetFocus
End If
txtUserAnswer.Text = ""
Else ' preparing to exit game
strName = InputBox("What is your name?")
' appending file with player's name & score
Open "Z:\Basic\Ch 9\Ch9Demo4\ch9demo4scores.txt" For Append As #2
Print #2, strName & " " & mintScore
Close #2
cmdDisplay_Click
For Each frmForm In Forms ' closing all VB forms
Unload frmForm
Next
End If
End Sub
Private Sub cmdDisplay_Click()
' displays previous scores to game
Dim strScoreAndName As String ' player's score concatenated with his name
Open "Z:\Basic\Ch 9\Ch9Demo4\ch9demo4scores.txt" For Input As #2
Do Until (EOF(2))
Input #2, strScoreAndName
frmScores.lstScoresAndNames.AddItem strScoreAndName
Loop
Close #2
frmScores.Show vbModal ' The optional vbModal parameter is used
' to force the user to close the second
' VB form before the VB unloads the project
End Sub
' 1. Note that the Sorted property of the listbox lstScoresAndNames was set to True at
' design time so that the names are in order
' 2. A general procedure should be used instead of the "hidden" command button cmdDisplay's
' Click event procedure. But we haven't learned about general procedures yet.
' 3. Notice the use of
' frmScores.lstScoresAndNames.AddItem strScoreAndName
' to add an item to the listbox which is on another VB form.
' 4. The Show method is used to show a second VB form (frmScores). However vbModal is used
' instead of vbModeless to require the user to close that form (with the x button in
' the upper-right corner) before the whole project unloads.
' 5. When a project uses more than one VB form, the special For Each loop MUST be used so
' that forms are left accidentally in the memory of the computer.
' Dim frmForms As Form
' For Each frmForm In Forms
' Unload frmForm
' Next