maskedtextbox.vb

来自「Samples are organized by chapter, and th」· VB 代码 · 共 63 行

VB
63
字号
Public Class MaskedTextBox
    Inherits TextBox

    Private _Mask As String
    Public Property Mask() As String
        Get
            Return _Mask
        End Get
        Set(ByVal Value As String)
            _Mask = Value
            Me.Text = ""
        End Set
    End Property

    Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
        If Mask = "" Then Exit Sub

        ' Suppress the typed character.
        e.Handled = True

        ' Loop through the mask, adding fixed characters as needed.
        ' If the next allowed character matches what the user has
        ' typed in (a number or letter), that is added to the end.
        Dim i As Integer
        Dim NewText As String = Me.Text
        For i = Me.SelectionStart To _Mask.Length - 1
            Select Case _Mask.Chars(i)
                Case "#"
                    ' Allow the keypress as long as it is a number.
                    If Char.IsDigit(e.KeyChar) = True Then
                        NewText &= e.KeyChar.ToString()
                        Exit For
                    Else
                        ' Invalid entry; exit and don't change the text.
                        Exit Sub
                    End If
                Case "."
                    ' Allow the keypress as long as it is a letter.
                    If Char.IsLetter(e.KeyChar) = True Then
                        NewText &= e.KeyChar.ToString()
                        Exit For
                    Else
                        ' Invalid entry; exit and don't change the text.
                        Exit Sub
                    End If
                Case Else
                    ' Insert the mask character.
                    NewText = NewText & _Mask.Chars(i)
            End Select
        Next

        Me.Text = NewText
        Me.SelectionStart = Me.Text.Length
        
    End Sub

    Protected Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
        ' Stop special characters.
        e.Handled = True
    End Sub

End Class

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?