Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Static tam As Integer
Static noChange As Boolean
If noChange = False Then
If TextBox1.TextLength > tam Then
If TextBox1.TextLength - tam = 1 Then ' el texto se introdujo por teclado o sólo se pegó un carácter...
If TextBox1.TextLength = 4 Or TextBox1.TextLength = 11 Then
tam = TextBox1.TextLength + 1
' aquí podrías poner también el nochange=true y después de la siguiente línea el =false
TextBox1.Text += "-"
TextBox1.SelectionStart = TextBox1.TextLength ' si eliminas esta línea el cursor se irá al inicio...
End If
Else ' se ha pegado texto.. ya que el teclado dispara el evento carácter a carácter...y se han añadido más de 1 de golpe.
If TextBox1.TextLength > 3 Then
Dim txt As String ' para valores temporales
txt = TextBox1.Text.Replace("-", "") ' elimina guiones (por si no existieran en el lugar adecuado)
Select Case txt.Length
Case 3
txt &= "-"
Case 4 To 9
txt = txt.Substring(0, 4) & "-" & txt.Substring(4, txt.Length - 4)
Case 10
txt = txt.Substring(0, 4) & "-" & txt.Substring(4, 6) & "-"
Case Is > 10
txt = txt.Substring(0, 4) & "-" & txt.Substring(4, 6) & "-" & txt.Substring(10, txt.Length - 10)
End Select
noChange = True
TextBox1.Text = txt
TextBox1.SelectionStart = TextBox1.TextLength ' olvidé meter esta línea.... para que el cursor se vaya al final de la edición.
noChange = False
End If
End If
End If
tam = TextBox1.TextLength
End If
End Sub