Code
for any Text Keypress Event
Masked Text Controls Sample
Sub Text1_KeyPress (KeyAscii As Integer) ' only allows numeric
Select Case KeyAscii ' Allow carriage return
Case 13 ' Set keyascii zero to prevent beeping
KeyAscii = 0 ' Allow backspace
Case 8
Case Else ' numeric character?
If IsNumeric(Chr$(KeyAscii)) Then ' Processing on string
Else
Beep ' Setting KeyAscii code to zero prevents illegal character from being displayed
KeyAscii = 0
End If
End Select
End Sub
You can expand on this method and display all alphabetic characters entered into the text control in uppercase. For example:
Sub Text1_KeyPress (Keyascii As Integer)
Keyascii = Asc( UCase$(Chr$(Keyascii)))
End Sub
That code ensures that alphabetic characters are always in uppercase, converts ANSI character code to the string equivalent using the chr$() function and changes the character entered to uppercase and revert back to ANSI character code using the ASC function.
There is another method to change the alphabetic characters to uppercase using DLL's - which I'll use in my next article if there are enough requests :soongc@gui.com.au. And please explain why you would want to use DLLs instead of this basic no-over-head method (or maybe you should skip the explanation).
A further expansion of the above method is to restrict the user from entering characters other than Y or N (y and n are converted to uppercase), demonstrated by the following code:
Sub Text1_KeyPress (KeyAscii As Integer) ' Only Y or N
Dim lChar As String * 1 ' Change to the uppercase character before doing any comparisons
lChar = UCase$(Chr$(KeyAscii)) ' Determine if the character entered is Y or N
If lChar = "Y" Or lChar = "N" Then
' display uppercase of Y or N
KeyAscii = Asc(lChar) ' Further processing
Else ' Warn user with a beep
Beep ' Disregard the character entered by the user
KeyAscii = 0
End If
End Sub
Before rushing off to buy a DLL or VBX, please consider...
![]()