VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

Systems Analysis - System analysis and Design tutorial for Software Engineering

You are here: Visual Basic > Advanced VB6 tutorial > Chapter 5

The KeyUp and KeyDown Events in Visual Basic 6

The KeyDown and KeyUp events happen when the user respectively presses and releases a key on the keyboard. Their event procedures take the following two parameters:
  • KeyCode contains an integer code for the physical key that the user pressed. You can check for a particular key by comparing KeyCode with one of the special VB internal constants for physical key codes. Each constant name begins with the string "vbKey" followed by an obvious name for the key (the letter of the key if it's an alphabetic key or some other obvious name for other keys). Examples of vbKey constants would be vbKeyA, vbKeyW, vbKeyF1, vbKeyPgUp, and so forth.

  • Shift indicates if any of the three shift keys (Alt, Ctrl, or Shift) is pressed at the moment. This parameter works in the same way as the Shift parameter for the MouseDown and MouseUp event procedures. That is, Shift is an integer representing a bit mask. You can extract information concerning the state of each of the three control keys by ANDing the Shift parameter with one of the three VB constants for the control keys.

In Listing 5.3, the KeyDown event procedure is used to detect when the user keys Shift+F10. Note the use of internal VB constants to detect the keystroke and the state of the Shift key.


Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Dim blnIsShift As Boolean
blnIsShift = Shift And vbShiftMask
If blnIsShift And (KeyCode = vbKeyF10) Then
'take some action for Shift+F10
End If
End Sub

NOTE :- How to Discover the Names of VB Keystroke Constants When in design mode, you can see the names of the internal VB keystroke constants by invoking the Object Browser with the F2 key, choosing All Libraries or VBRun from the Libraries/Projects list, and then choosing KeyCodeConstants from the Classes list, as shown in Figure 5.1

Finding the names of VB KeyCode constants in the Object Browser
FIGURE 5.1 Finding the names of VB KeyCode constants in the Object Browser

In the event procedure code, you can modify the values of the KeyCode and Shift parameters to change the keystroke information that the system sees, just as you can modify the KeyAscii parameter in the KeyPress event procedure.

Keystroke Events at Field and Form Level topics

See Also


<< Previous | Contents | Next >>

Home | About Us | Privacy Policy | Contact Us

Copyright © | All Rights Reserved