http://www.vb-helper.com/HowTo/numonly.zip

	Purpose
Make a TextBox accept only digits

	Method
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.

1. 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.

    Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    Private Const GWL_STYLE = (-16)
    Private Const ES_NUMBER = &H2000

Now if you type a non-digit, the control ignores it.

2. In the TextBox's KeyPress event, look for Control-V. When you see it,
change KeyAscii to 0 so it is ignored.

    ' Ignore Control-V keys.
    Private Sub Text1_KeyPress(KeyAscii As Integer)
    Const CTRL_V = 22

        If KeyAscii = CTRL_V Then KeyAscii = 0
    End Sub

3. This one is work. Subclass the control so a new WindowProc runs when the
control receives events.

    OldWindowProc = SetWindowLong( _
        Text1.hWnd, GWL_WNDPROC, _
        AddressOf NewWindowProc)

When the new WindowProc receives any message other than WM_CONTEXTMENU, it
invokes the control's original WindowProc. It ignores WM_CONTEXTMENU
messages.

    Public Function NewWindowProc(ByVal hWnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
        If msg <> WM_CONTEXTMENU Then _
            NewWindowProc = CallWindowProc( _
                OldWindowProc, hWnd, msg, wParam, _
                lParam)
    End Function

Thanks to Nikos Dimopoulos (Nikos.Dimopoulos@fimat.co.uk) for the tip about
SetWindowLong and ES_NUMBER.

	Disclaimer
This example program is provided "as is" with no warranty of any kind. It is
intended for demonstration purposes only. In particular, it does no error
handling. You can use the example in any form, but please mention
www.vb-helper.com.
