|  |  | 
              
              | 
                  | Title | Make a TextBox allow only letters and numbers | 
|---|
 | Keywords | TextBox, letters, numbers, field, validate, context menu, popup | 
|---|
 | Categories | Controls, 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 |  |  |  |   |  |  |  |  |