There are many routines for restricting numeric entry into an editbox to numbers and ". and -", but I wanted something that would error check as you entered the characters one by one and would also display entries of ".123" as "0.123" and "-.123" as "-0.123". The routine would also have to ensure entry of only one "-" and this would be at the beginning of the number. The routine would also have to ensure that only one "." could be entered and it must also allow editing.
I believe the following code does this, so I hope it will be of use to anyone looking for this type of entry.
Code: Select all
'=============================================
' NUMERIC INPUT IN A TEXTBOX
' This does a check for 0-9 and - or . and prevents entry of all other
' characters. It ensures that "-" can only be placed at the start of
' the number entry. It also ensures that only one "." or "-" can be
' entered.
' It also ensures that if .123 is entered it displays 0.123 and if
' -.123 is entered -0.123 is displayed.
' Code by RNBW.
'============================================
#Include "WinGUI.bi"
Dim As HWND Window_Main, Button_Ok, Edit_1
Dim As MSG msg
dim As String txt, oldtxt
Dim As Integer pos0
Function num(ByVal txt As String) As String
'Function to check that character input is 0-9, - or .
Dim As String num1
Dim As Integer i, a, t
For i = 1 To Len(txt)
a = Asc(Mid(txt,i,1))
if a = 46 then t = t + 1
if (a = 46) and (t > 1) then a = 0 'only DOT after FIRST is cleared
if a = 45 and i>1 then a = 0 'so really almost anything do, not just 8
if a = 46 and i = 1 then num1 = "0" + num1
If a = 45 Or a = 46 or a > 47 and a < 58 then num1 = num1 + Chr(a)
Next
a=asc(mid(txt,1,1))
if a = 45 and mid(txt,2,1) = "." then num1 = "-0" + num1
Return num1
End Function
'Create a window with an Editbox and a button:
Window_Main = Window_New (100, 100, 400, 400, "Numeric Entry Filter!")
Var Label_txt = Label_New (10, 10, 150, 20, "Enter numbers:",, Window_Main)
Edit_1 = EditBox_New (150, 10, 100, 20, "",, Window_Main)
Button_Ok = Button_New (160, 300, 60, 20, "Ok",, Window_Main)
'Set timer to 300 miliseconds:
SetTimer(Window_Main, 0, 300, 0 )
Do
WaitEvent(Window_Main,msg)
Select Case msg.message
Case WM_TIMER
'Check contents of the edit box every 300 millisecinds
txt = EditBox_GetText(Edit_1) 'get text from edit box
oldtxt = txt 'make text the oldtext
txt = num(txt) 'gets new text from function num(txt) which does the checking
If oldtxt <> txt Then
EditBox_SetText(Edit_1, txt) 'if old text is not the same as the new text then use new text
pos0 = Len(txt) 'position of character is the length of the current text
SendMessage(Edit_1, EM_SETSEL, pos0, pos0)
End If
Case WM_LBUTTONDOWN
If msg.hwnd = Button_Ok Then Print EditBox_GetText(Edit_1) 'print text to console
End Select
Loop Until Window_Event_Close(Window_Main, msg)
End