4

我是 Visual Basic 的新手,我不确定如何禁用字母和特殊字符。

我只希望用户能够输入数字。

我正在使用此代码,我知道有一种更简单的方法可以做到这一点,感谢所有帮助

当我输入字母字符和输入数字时,我得到消息框。当我输入数字时,我不想得到消息框。

Private Sub txtCustom_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCustom.KeyDown

    If (e.KeyCode = Keys.Enter) Then

        e.SuppressKeyPress = True

        If (e.KeyCode = Keys.A Or Keys.B Or Keys.C Or Keys.D Or Keys.E Or Keys.F Or Keys.G Or Keys.H Or Keys.I Or Keys.J Or Keys.K Or Keys.L Or Keys.M Or Keys.N Or Keys.O Or Keys.P Or Keys.Q Or Keys.R Or Keys.S Or Keys.T Or Keys.U Or Keys.V Or Keys.W Or Keys.X Or Keys.Y Or Keys.Z) Then

            Beep()
            MsgBox("Please Input A Numerical Value")
            txtCustom.Text = ""

        Else

            RandNumAllow = txtCustom.Text

        End If

    End If

End Sub
4

3 回答 3

7

尝试改用 KeyPress 事件:

Private Sub TextBox1_KeyPress(sender As Object, _
                              e As KeyPressEventArgs) Handles TextBox1.KeyPress
  e.Handled = Not Char.IsNumber(e.KeyChar)
End Sub

但这不会阻止某人使用剪贴板。改用 MaskedTextBox 控件可能会更好。

于 2012-10-21T13:35:54.577 回答
0

很抱歉,此代码将解决所有问题,从剪贴板复制和特殊字符的 shift + 数字,因为它使用 TextChanged 事件尝试一下。

    Dim charactersAllowed As String = "1234567890"
      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Dim theText As String = TextBox1.Text
    Dim Letter As String
    Dim SelectionIndex As Integer = TextBox1.SelectionStart
    Dim Change As Integer
    For x As Integer = 0 To TextBox1.Text.Length - 1
        Letter = TextBox1.Text.Substring(x, 1)
        If charactersAllowed.Contains(Letter) = False Then
            SystemSounds.Beep.Play()
            theText = theText.Replace(Letter, String.Empty)
            Change = 1
        End If
    Next
    TextBox1.Text = theText
    TextBox1.Select(SelectionIndex - Change, 0)
End Sub

您可以将 charractersAllowed 的值替换为您希望允许的任何字符

于 2018-02-22T17:17:03.217 回答
0

您正在寻找的代码我认为看起来像这样。

对于您尝试控制输入的任何文本或输入框上的按键事件

If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso 'restricts anything but number keys
    e.KeyChar <> ControlChars.Back Then 'allows use of backspace
    e.Handled = True
End If
于 2019-05-07T14:26:40.967 回答