Monday, July 24, 2000

Programming Tips & Tricks #0007---Global Keyboard Handler in Visual Basic

Tips & Tricks #0007

Global Keyboard Handler in Visual Basic

One of the questions that I am frequently asked is how to implement Keystroke validation in a Visual Basic Textbox. The answer is that you can insert code into the KeyPress Event Procedure of a Textbox--and implement Keystroke validation that way. For instance, this code will ensure that only numbers are entered into a Textbox---it also permits the user to press enter a BackSpace key in case they make a mistake.

Private Sub Text1_KeyPress(KeyAscii As Integer)

If KeyAscii = 8 Then Exit Sub '8 is Backspace

If KeyAscii <> 57 Then 'Range of numeric values
KeyAscii = 0
End If

End Sub

Entering code into the KeyPress Event Procedure of a Textbox is fine for one or two Textboxes---but If you have a large number of Textboxes on your form, this is not an enviable task. In that case, you have two alternatives:

First, you can make each Textbox a member of a Textbox Control Array, in which case each Textbox 'shares' the same KeyPress Event Procedure. Sharing code like that is the chief benefit of a Control Array.

The second alternative is to set up a Form Level or Global Keyboard Handler by telling Visual Basic that you want the Form's KeyPress Event Procedure to be triggered BEFORE the individual Textbox KeyPress Event Procedures.

You do this by setting the KeyPreview Property of the Form to True. This will cause the KeyPress Event Procedure of the Form to be triggered whenever a keystroke is made for any of the Textboxes on the form. What that means is that you can take the code you write for each Textbox KeyPress Event on your form--and place it in just one place---the KeyPress Event Procedure of the Form.

No comments: