In previous lessons, we have only learned how to trigger events or control program flow by clicking the mouse. In this chapter, you will learn how to use the keyboard to trigger an event using the keyboard beside using the mouse. When the user presses a key on the keyboard, it will trigger an event or a series of events. These events are called the keyboard events. In Visual Basic, the three basic event procedure to handle the keyboard events are KeyPress, Keydown and KeyUp
The keyboard event occurs when the user presses any key that corresponds to a certain alphanumeric value or an action such as Enter, spacing, backspace and more. Each of those value or action is represented by a set of code known as the ASCII . ASCII stands for American Standard Code for Information Interchange. ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose.In order to write code for the Keyboard events , we need to know the ASCII and the corresponding values. Some of the commond ASCII values are shown in Table 38.1.
Table 38.1: ASCII Values
For more detail table, please refer to http://www.asciitable.com/
38.2 Common Key Events Constants.
In Visual Basic 6, it employs a set of constants that correspond to the ASCII values. We can use the constants instead of the ASCII. The following tablle shows the constants and the corresponding ASCII values.
38.3 Writing code for the key events
We can write code for the three key events i.e. keyPress, KeyDown and KeyUp.
In this example, the program can detect the pressing of Enter key and the keys other than the Enter key.
If you wish to detect and display the key pressed by the user, simply type the following code:
The function Chr will convert the ASCII values to the corresponding characters as shown in the ASCII table.
In this example, we use the For ...Next loop to display the alphabet A to Z by pressing any key on the keyboard.
Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved |Contact: firstname.lastname@example.org