Numeric or Currency TextBox

Started by Paul Squires, September 23, 2011, 01:54:10 PM

Previous topic - Next topic

Paul Squires

A common question is how to filter out unwanted characters from a TextBox. For example, say you need a TextBox to only accept a currency value, then you would allow numbers and the period. Here is an easy way to do it in FireFly (easy, because FireFly already handles the subclassing for you).


'--------------------------------------------------------------------------------
Function FORM1_TEXT1_WM_CHAR ( _
                             ControlIndex  As Long,  _  ' index in Control Array
                             hWndForm      As Dword, _  ' handle of Form
                             hWndControl   As Dword, _  ' handle of Control
                             chCharCode    As Long,  _  ' character code
                             lKeyData      As Long   _  ' key data
                             ) As Long

     
   ' If the key pressed is not valid then the WM_CHAR handler
   ' will return TRUE thereby stopping processing of that key.
   Function = ProcessTextBoxKeys( hWndControl, chCharCode )
   
End Function


'--------------------------------------------------------------------------------
Function ProcessTextBoxKeys( ByVal hWndControl As Dword, _
                             ByVal chCharCode  As Long _
                             ) As Long
                             
   ' This function is called from the WM_CHAR message handler for
   ' the TextBox wanting to filter numeric data.
   
   Local fHasPeriod As Long
   Local i          As Long
   Local st         As String
   
   
   st = FF_TextBox_GetText( hWndControl )
   
   fHasPeriod = Instr(st, ".")
   
   Select Case chCharCode
      Case 8     ' backspace (always allow)
         
      Case 48 To 57, 8    ' numbers
         ' only allow two digits after the period
         If fHasPeriod Then
            If Len(Mid$(st, fHasPeriod+1)) >= 2 Then Function = %TRUE
         End If   
         
      Case 46   ' period (only allow one)
         If fHasPeriod Then Function = %TRUE
         
         ' Don't allow the period to be placed any further back than
         ' the last two numbers.
         i = FF_TextBox_GetSelStart( hWndControl ) + 1     
         If Len(st) - i >= 2 Then Function = %TRUE
           
   
      Case Else  ' don't allow anything else
         Function = %TRUE
         
   End Select
                             
End Function
             

Paul Squires
PlanetSquires Software

Paul Squires

This type of numeric/currency TextBox looks best when the TextBox has the ES_RIGHT WindowStyle set.
Paul Squires
PlanetSquires Software