Visual Basic Version: VB 4.0, VB 5.0, VB 6.0
Issue: The standard text box does not provide for any specification of a data type. Any alphabetic, numeric or special character keys can be entered into a text box. However, there may be times when you only want to allow entry of numeric values or only alphabetic characters.
Code:
' Ensure the entered data is numeric
Sub txtName_KeyPress (KeyAscii As Integer)
Select Case KeyAscii
' Allow a number
Case 48 To 57
' OK, do nothing
' Allow edit keys
Case vbKeyBack
' OK, do nothing
' Don't allow anything else
Case Else
Beep
KeyAscii = 0
End Select
End Sub
Note: This code will also work in VB3 if the constant vbKeyBack is defined to be 8.
Visual Basic Version: VB 3.0 and VB 4.0 (16-bit)
Issue: There may be times when your application needs to capture the tab key. You may want to change the tab order under specific circumstances, allow the user to use the Tab key within a text box to move to the next tab stop instead of the next field, and so on.
This is not an easy task because the TAB does NOT generate the Key_Press event. So, you need to use the GetKeyState windows API function for this. This may also work in VB 4.0 32-bit with the correct change to the API call. This was not tested.
Code:
Declare Function GetKeyState% Lib "User" (ByVal
nVirtKey%)
' Virtual key values
Global Const VK_TAB = &H9
Global Const VK_SHIFT = &H10
Sub txtAreaCode_LostFocus ( ) Dim iRetVal as Integer ' Check for a tab out of this control to mess with the tab order ' Skip the area code field iRetVal = GetKeyState(VK_SHIFT) ' If the shift was NOT on, check the tab If iRetVal <> -128 And iRetVal <> -127 Then iRetVal = GetKeyState(VK_TAB) If iRetVal = -128 Or iRetVal = -127 Then ' tab key pressed txtPhone.SetFocus End If End If End Sub
Visual Basic Version: VB 3.0 and VB 4.0
Issue: Many users want to press the Enter key instead of the Tab key to move from field to field on a form. Even though this is not a windows standard, this is a popular request.
The trick to this one is to remember to set KeyAscii = 0. Otherwise the user will get a beep each time the Return key is pressed.
Code:
Sub txtName_KeyPress (Index As Integer, KeyAscii As Integer) ' Convert RETURN to TAB If KeyAscii = KEY_RETURN Then ' Needed to prevent the beep KeyAscii = 0 ' Generate a TAB to move to the next field SendKeys Chr$(9) End If End Sub
| All contents © 2004 InStep Technologies, Inc. All rights reserved. |