1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
Private Sub KeypressNombre(ByVal e As System.Windows.Forms.KeyPressEventArgs)
Try
If Asc(e.KeyChar) = 8 Then Exit Sub /// retour arrière
If InStr("0123456789.,-", e.KeyChar) = 0 Then /// autorisation des chiffres, des virgules et du moins (3 cas ci après)
e.KeyChar = CType("", Char)
Exit Sub
End If
/// !!! raisonnement prenant aussi en compte une sélection dans le TextBox !!!
Dim monTexteAvant As String
monTexteAvant = Microsoft.VisualBasic.Left(Me.Text, Me.SelectionStart)
Dim CaracVirgule As Char
CaracVirgule = CType(My.Application.Culture.NumberFormat.NumberDecimalSeparator, Char)
/// /\ chiffre tapé /\
If InStr("0123456789", e.KeyChar) > 0 Then
If Me.SelectionStart = 0 And InStr(monTexteAvant, "-") > 0 Then /// si on est au début et qu'il y a un moins, on ne laisse pas taper un chiffre avant !
e.KeyChar = CType("", Char)
Exit Sub
End If
/// gestion du nombre de décimal si on vient de taper un chiffre
If InStr(monTexteAvant, CaracVirgule) > 0 Then /// regarde s'il y a une virgule avant le chiffre tapé
If Len(Mid(Me.Text, InStr(Me.Text, CaracVirgule) + 1)) - Me.SelectionLength >= NombreDecimales Then
/// = si nombre de chiffre après la virgule est deja au max alors on en rajoute plus (on ne compte pas ceux qui sont sélectionnés et qui seront supprimés)
e.KeyChar = CType("", Char)
Exit Sub
End If
End If
/// reste chiffre et on autorise
Exit Sub
End If
/// /\ virgule tapée /\
If e.KeyChar = "." Or e.KeyChar = "," Then
If NombreDecimales = 0 Then /// si on autorise 0 décimales alors meme pas de virgule ... forcément ...
e.KeyChar = CType("", Char)
Exit Sub
End If
If InStr("0123456789", Microsoft.VisualBasic.Right(monTexteAvant, 1)) = 0 Then /// virgule autorisée seulement si c'est un chiffre placé avant
e.KeyChar = CType("", Char)
Exit Sub
End If
If InStr(Me.Text, CaracVirgule) > 0 And InStr(Me.SelectedText, CaracVirgule) = 0 Then
/// interdiction s'il y a deja une virgule dans le TextBox et pas dans la sélection
e.KeyChar = CType("", Char)
Exit Sub
End If
/// virgule autorisée (et transformée)
e.KeyChar = CaracVirgule /// on vient de taper une virgule et on a le droit alors on sort
Exit Sub
End If
/// /\ [moins] tapé /\
If e.KeyChar = "-" Then /// gestion du moins
If Me.SelectionStart > 0 Then /// si on est pas au début de la zone de saisie on sort
e.KeyChar = CType("", Char)
Exit Sub
End If
If InStr(Me.Text, "-") > 0 And InStr(Me.SelectedText, "-") = 0 Then /// interdiction s'il y a deja un moins dans le TextBox et pas dans la sélection
e.KeyChar = CType("", Char)
Exit Sub
End If
/// moins autorisé
Exit Sub
End If
Catch ex As Exception
Erreur.Trace(ex, Me, e)
e.KeyChar = CChar("")
End Try
End Sub |
Partager