segunda-feira, 2 de julho de 2012

Colocando uma máscara de hora em um Textbox

'Cancelar as teclas de letras, acentos e outros caracteres não numéricos
If Not Char.IsNumber(e.KeyChar) And e.KeyChar <> Chr(8) And e.KeyChar <> Chr(13) Then
      e.Handled = True
End If

'Máscara de data com a barra
If IsNumeric(e.KeyChar) = True Then
      Select Case TextBox1.TextLength
            Case 0
                  TextBox1.Text =
""
            Case 2
                  TextBox1.Text = TextBox1.Text +
":"
                  TextBox1.SelectionStart = 4

      End Select
End If

'Limita o textbox a 5 caracteres
If TextBox1.TextLength = 5 Then
      If Not e.KeyChar = Chr(8) Then
            e.Handled =
True
            TextBox1.SelectionStart = TextBox1.TextLength

      End If
End If

'Retirar o : das posições e o número anterior quando Backspace é pressionada
If
TextBox1.TextLength &lt;&gt; 0 Then
      If e.KeyChar = Chr(8) And TextBox1.TextLength = TextBox1.Text.LastIndexOf(":") + 1 Then
            TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.TextLength - 1)
            TextBox1.SelectionStart = TextBox1.TextLength

      End If
End If

2 comentários:

  1. Você poderia usar a propriedade "MaxLenght=5"
    Ao invés de

    'Limita o textbox a 5 caracteres
    If TextBox1.TextLength = 5 Then
    If Not e.KeyChar = Chr(8) Then
    e.Handled = True
    TextBox1.SelectionStart = TextBox1.TextLength
    End If
    End If

    Também é possível.

    ResponderExcluir