' Mr. Minich
' Period 1
' Ch4Demo1
' 11/2/2000
' Purpose - to illustrate the use of the KeyPress event and an If/ElseIf statement
Option Explicit
Private Sub Form_Activate()
' displaying appropriate messages & setting visibility
lblMessage.AutoSize = True ' allows message to fit into labels without being
lblWarning.AutoSize = True ' cut off
' setting various captions
lblMessage.Caption = "Press a to add 1" & vbCrLf & "Press s to subtract 1"
lblRunningTotal.Caption = "0"
lblWarning.Caption = "Press 'a' to add one and 's' to subtract one"
cmdExit.Caption = "Exit"
cmdClear.Caption = "&Clear"
lblWarning.Visible = False ' warning should be invisible at first
frmMain.KeyPreview = True ' necessary for KeyPress to work with
' command buttons on the form
End Sub
Private Sub Form_KeyPress(KeyAscii As Integer)
' adds or subtracts one depending on the user's keypress
' KeyAscii is the parameter used to store the ASCII value of the key
' that was pressed by the user.
lblWarning.Visible = False ' make warning invisible in case it was visible
If (KeyAscii = 97) Then ' if a is pressed add one
lblRunningTotal.Caption = Val(lblRunningTotal.Caption) + 1
ElseIf (KeyAscii = 115) Then ' if s is pressed subtract one
lblRunningTotal.Caption = Val(lblRunningTotal.Caption) - 1
Else ' show warning if wrong key pressed
lblWarning.Visible = True
End If
End Sub
Private Sub cmdClear_Click()
' clear running total label
lblRunningTotal.Caption = "0"
End Sub
Private Sub cmdExit_Click()
' unload form and exit project
Unload Me
End
End Sub
' Notes:
' vbCrLf is the Visual Basic "Carriage Return/Line Feed constant" that allows you to
' break up Caption settings over two or more lines.
' KeyAscii is the default name for the parameter of the KeyPress event. It is not
' recommended that you change this parameter name for any reason but do realize
' that is simply the numerical ASCII value of the key which was pressed by the user.
' In effect, the statement
' lblRunningTotal.Caption = Val(lblRunningTotal.Caption) + 1
' is a counter statement. It allows for the running total to be stored and displayed in the caption
' of the label lblRunningTotal. Each time it is executed, one is added to the existing value stored
' in the caption.