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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12813025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:20:48  来源:igfitidea点击:

How to allow the space key and backspace key in VB.NET/ Visual Studio 2008?

vb.net

提问by Prakash Banjara

How do I allow the space key and backspace key in VB.NET/ Visual Studio 2008?

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

Sample code:

示例代码:

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

回答by Mark Hall

For Backspace use the AscFunction and test for the Hex Value, in this case 8, for the Space you can just test for " "

对于 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

If your question is how to check BackSpace and Space the above answer will work. To allow them along with your Text then do something like this

如果您的问题是如何检查 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

回答by Liong

Work at Visual Studio 2012:

在 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