Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleUse a new WindowProc and SetWindowLong to make a TextBox accept only digits
DescriptionThis example shows how to use a new WindowProc and SetWindowLong to make a TextBox accept only digits in Visual Basic 6.
KeywordsTextBox, only digits, numeric field, SetWindowLong, WindowProc, subclassing
CategoriesControls, API
 
There are three ways the user can enter text into a TextBox: typing, pressing ^V to paste text, and right clicking and selecting Paste from the control's context menu.

To allow only text while typing, use GetWindowLong to get the TextBox's Window style. Then use SetWindowLong to add on the style ES_NUMBER. Now if you type a non-digit, the control ignores it.

To prevent pasting or using the context menu, subclass the control. In the new WindowProc, ignore WM_PASTE and WM_CONTEXTMENU messages.

Thanks to Michael Rosquist for the tip about putting the test for WM_PASTE in the WindowProc.

 
Private Sub Form_Load()
Dim style As Long

    ' Get the current style.
    style = GetWindowLong(Text1.hWnd, GWL_STYLE)

    ' Add ES_NUMBER to the style.
    SetWindowLong Text1.hWnd, GWL_STYLE, style Or ES_NUMBER

    ' Subclass to ignore the context menu.
    OldWindowProc = SetWindowLong( _
        Text1.hWnd, GWL_WNDPROC, _
        AddressOf NewWindowProc)
End Sub

Public Function NewWindowProc(ByVal hWnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, ByVal lParam As Long) As _
    Long
    If (msg <> WM_PASTE) And (msg <> WM_CONTEXTMENU) Then
        NewWindowProc = CallWindowProc( _
            OldWindowProc, hWnd, msg, wParam, _
            lParam)
    End If
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated