VB.NET - 检查按下的键是否与标签中的文本相同

VB.NET - Check if the key pressed is the same as the text in label

不知道有没有人能帮我做一下上面的问题

基本上我所拥有的是一个标签,其中放置了一个随机生成的字母。

我想要做的是在按下标签中的同一个键时显示一个消息框(只是为了表明它现在可以工作)。我尝试了两种方法,但 none 似乎有效,有人能指出我正确的方向吗?好像没那么难,我刚接触编码。

Private Sub speedtyping_Keydown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

    If (e.KeyChar = lblletter1.Text.ToString) Then
        MsgBox("WORKS")
    ElseIf (e.KeyChar = lblletter2.Text) Then
        MsgBox("words")
    End If

非常感谢!

试试这个

Private Sub speedtyping_Keydown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

If (e.KeyChar.ToString = lblletter1.Text) Then
    MsgBox("WORKS")
ElseIf (e.KeyChar.ToString = lblletter2.Text) Then
    MsgBox("words")
End If

End Sub

试试这个

Private Sub speedtyping_Keydown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

If (e.KeyChar.Trim() = lblletter1.Text.Trim()) Then
    MsgBox("WORKS")
ElseIf (e.KeyChar.Trim() = lblletter2.Text.Trim()) Then
    MsgBox("words")
End If

End Sub

为了处理表单的 KeyPress 事件,您需要将其设置为 KeyPreview 属性。您可以在表单设计器或表单的 Load 事件处理程序中执行此操作,如下所示。

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.KeyPreview = True
    End Sub

    Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If e.KeyChar = lblletter1.Text(0) Then
            MessageBox.Show("WORKS")
        ElseIf e.KeyChar = lblletter2.Text(0) Then
            MessageBox.Show("words")
        End If
    End Sub
End Class