Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
 
 
 
500MB 27GB Web Hosting - $9.95/Month
 
 
 
 
 
Old Pages
 
Old Index
Site Map
What's New
 
Books
How To
Tips & Tricks
Tutorials
Stories
Performance
Essays
Links
Q & A
New in VB6
Free Stuff
Pictures
 
 
 
TitleMake a TextBox allow only letters and numbers
KeywordsTextBox, letters, numbers, field, validate, context menu, popup
CategoriesControls, Tips and Tricks, API
 
In the TextBox's KeyPress event, look for characters that are not letters or numbers and discard them by setting KeyAscii to 0.
 
' Allow only letters and numbers.
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim ch As String

    ch = Chr$(KeyAscii)
    If Not ( _
        (ch >= "a" And ch <= "z") Or _
        (ch >= "A" And ch <= "Z") Or _
        (ch >= "0" And ch <= "9") _
    ) Then
        ' Cancel the character.
        KeyAscii = 0
    End If
End Sub
 
To prevent the user from right clicking on the TextBox and using the context menu to paste invalid characters, subclass the TextBox and discard WM_CONTEXTMENU messages.
 
' Pass along all messages except the one that
' makes the context menu appear.
Public Function NoPopupWindowProc(ByVal hWnd As Long, ByVal _
    Msg As Long, ByVal wParam As Long, ByVal lParam As _
    Long) As Long
Const WM_NCDESTROY = &H82
Const WM_CONTEXTMENU = &H7B

    ' If we're being destroyed,
    ' restore the original WindowProc.
    If Msg = WM_NCDESTROY Then
        SetWindowLong _
            hWnd, GWL_WNDPROC, _
            OldWindowProc
    End If

    If Msg <> WM_CONTEXTMENU Then _
        NoPopupWindowProc = CallWindowProc( _
            OldWindowProc, hWnd, Msg, wParam, _
            lParam)
End Function
 
 
Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated