VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Force Numeric Entry in a Text Box Using API

by Dion Campbell (1 Submission)
Category: Windows API Call/Explanation
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (2 Votes)

This routine will cause a textbox control to accept only numeric input. Any other input (including the '-' and '.' keys) will be ignored. Note that it is still possible to paste non-numeric data into the textbox. There have been plenty of examples of this in the last couple of days - in the comments section of one of these someone suggested using the API. So, for anyone that is interested, this is one way of doing it...
I've put this in the intermediate category only because it uses API functions - otherwise it's straightforward code. I've only tested this in VB6.0 on Win2k, but it should work on any Windows platform from Win95 up.

API Declarations
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 ES_NUMBER = &H2000
Private Const GWL_STYLE = -16

Rate Force Numeric Entry in a Text Box Using API

Private Sub ForceNumeric(Box As TextBox)
  On Error GoTo Catch
  Dim nStyle As Long
  
  nStyle = GetWindowLong(Box.hWnd, GWL_STYLE)
  Call SetWindowLong(Box.hWnd, GWL_STYLE, nStyle Or ES_NUMBER)
  GoTo Finally
  
Catch:
  Call MsgBox(Err.Description, vbCritical Or vbOKOnly, "Error")
Finally:
End Sub

Download this snippet    Add to My Saved Code

Force Numeric Entry in a Text Box Using API Comments

No comments have been posted about Force Numeric Entry in a Text Box Using API. Why not be the first to post a comment about Force Numeric Entry in a Text Box Using API.

Post your comment

Subject:
Message:
0/1000 characters