2

如何在 VB.NET/Visual Studio 2008 中允许空格键和退格键?

示例代码:

Private Sub txtname_KeyPress(ByVal sender As System.Object, _
                             ByVal e As System.Windows.Forms.KeyPressEventArgs) _
                             Handles txtname.KeyPress

    If e.KeyChar < "A" Or e.KeyChar > "z" And e.KeyChar <> ControlChars.Back Then
        e.Handled = True
        txtname.Clear()
    Else
    End If
End Sub
4

2 回答 2

5

对于 Backspace 使用AscFunction 并测试Hex Value,在本例中为 8,对于 Space 你可以测试" "

If Asc(e.KeyChar) = 8 OrElse e.KeyChar = " " OrElse e.KeyChar < "A" OrElse e.KeyChar > "z" Then
    e.Handled = True
    CType(sender, TextBox).Clear()
End If

如果您的问题是如何检查 BackSpace 和 Space,则上述答案将起作用。要让它们与您的文本一起使用,请执行以下操作

If Not ((Asc(e.KeyChar) = 8 OrElse e.KeyChar = " ") OrElse (e.KeyChar >= "A" AndAlso e.KeyChar <= "z")) Then
    e.Handled = True
    CType(sender, TextBox).Clear()
End If
于 2012-10-10T07:12:03.807 回答
0

在 Visual Studio 2012 工作:

Private Sub Username_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Username.KeyPress
     If Not (Char.IsNumber(e.KeyChar) Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 32) Then
                e.Handled = True
     End If
End Sub
于 2020-02-29T12:27:26.613 回答