Only allow numeric values in the textbox

前端 未结 12 1012
南笙
南笙 2021-01-12 03:53

I want to make a TextBox control that only accepts numerical values.

How can I do this in VB6?

12条回答
  •  遥遥无期
    2021-01-12 04:07

    I let the API do it for me. I add this function to a .bas module and call it for any edit control that I need to set to numeric only.

    Option Explicit
    
    Private Const ES_NUMBER = &H2000&
    Private Const GWL_STYLE = (-16)
    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
    
    
    'set an editbox to numeric only - return the previous
    'style on success or zero on error
    Public Function ForceNumeric(ByVal EditControlhWnd As Long) As Long
        Dim lngCurStyle As Long
        Dim lngReturn As Long
    
        lngCurStyle = GetWindowLong(EditControlhWnd, GWL_STYLE)
        If lngCurStyle <> 0 Then
            lngReturn = SetWindowLong(EditControlhWnd, GWL_STYLE, lngCurStyle Or ES_NUMBER)
        End If
    
        ForceNumeric = lngReturn
    
    End Function
    

    To use it call the function with the handle of the TextBox.

    Private Sub Form_Load()
        Dim lngResult As Long
    
        lngResult = ForceNumeric(Text1.hwnd)
    
    End Sub
    

提交回复
热议问题