简体   繁体   English

按下空格键时如何清除文本框的所有内容? VB.Net

[英]How to clear all contents of textbox when spacebar is pressed? VB.Net

I'm creating a simple typing test program.我正在创建一个简单的打字测试程序。

I want the space bar to trigger checking if the typed word is correct, then clear the contents of the textbox.我希望空格键触发检查输入的单词是否正确,然后清除文本框的内容。

What happens here is the first typed word will work and be counted when the space bar is pressed and the typed word will be cleared, but the space character still remains and so the next typed word will contain a space char and will be read wrong.这里发生的是第一个输入的单词将起作用并在按下空格键时被计数并且输入的单词将被清除,但空格字符仍然存在,因此下一个输入的单词将包含一个空格字符并且将被错误读取。

I tried interchanging where the txtInput.Clear() should be placed but results in the same problem.我尝试交换应该放置txtInput.Clear()的位置,但导致了同样的问题。

Private Sub txtInput_TextChanged(sender As Object, e As KeyEventArgs) Handles txtInput.KeyDown

    If e.KeyValue = Keys.Space Then
        Space()
    End If

End Sub

Public Function Space()

    If txtInput.Text = txtWord.Text Then
        ctr = CInt(txtWord.TextLength)
        charTotal = charTotal + ctr
        lblScore.Text = charTotal.ToString
    End If

    txtInput.Clear()
    txtWord.Text = rdmWord()

End Function

In KewDown Event the value of TextBox isnot setted yet.KewDown Event中, TextBox的值尚未设置。 So, use KeyUp Event as the code below shows因此,使用KeyUp Event ,如下面的代码所示

Private Sub txtInput_KeyUp(sender As Object, e As KeyEventArgs) Handles txtInput.KeyUp
    If e.KeyValue = Keys.Space Then
        Space()
    End If
End Sub

You could also override ProcessCmdKey and trap the spacebar there:您还可以覆盖ProcessCmdKey并在此处捕获空格键:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    If keyData = Keys.Space Then
        If Me.ActiveControl Is txtInput Then
            Space()
            Return True ' suppress space
        End If
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

If you want to allow space or enter, then change to:如果要允许空格或输入,则更改为:

    If keyData = Keys.Space Or keyData = Keys.Enter Then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM