如何在VB.NET中处理KeyDown

时间:2009-07-24 13:51:05

标签: vb.net

好的,这是我的困境。这是我的代码:

   If e.KeyCode = Keys.A Then
        TextBox1.AppendText("C, ")
        PictureBox2.Visible = True
        My.Computer.Audio.Play(My.Resources.C, AudioPlayMode.Background)
   End If

现在当我在Form1_KeyDown下输入它时,visual basic认为:

'KeyCode不是'System.EventArgs'的成员

现在我已经看过这个代码了,但它不在这里。有什么帮助吗?

这是完整的代码:

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.KeyCode = Keys.A Then
        TextBox1.AppendText("A, ")
        PictureBox2.Visible = True
        My.Computer.Audio.Play(My.Resources.C, AudioPlayMode.Background)
    End If
    If e.KeyCode = Keys.S Then
        TextBox1.AppendText("C,")
        PictureBox14.Visible = True
        My.Computer.Audio.Play(My.Resources.D, AudioPlayMode.Background)
    End If
End Sub

4 个答案:

答案 0 :(得分:6)

不确定为什么方法定义将e声明为EventArgs,但修复只是创建KeyEventArgs类型的参数。这是因为EventArgs(自然地)不包含名为KeyCode的属性,但KeyEventArgs会这样做!

将事件处理程序方法定义更改为以下内容:

Private Sub foo_KeyDown(sender As Object, e As KeyEventArgs)
    If e.KeyCode = Keys.A Then
        TextBox1.AppendText("A, ")
        PictureBox2.Visible = True
        My.Computer.Audio.Play(My.Resources.C, AudioPlayMode.Background)
    ElseIf e.KeyCode = Keys.S Then
        TextBox1.AppendText("C,")
        PictureBox14.Visible = True
        My.Computer.Audio.Play(My.Resources.D, AudioPlayMode.Background)
    End If
End Sub

答案 1 :(得分:0)

听起来你的方法使用了错误的EventArgs。 Control.KeyDown事件将其作为System.Windows.Forms.KeyEventArgs发送。所以你的代码应该是

Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs)
   // code here
End Sub

答案 2 :(得分:0)

我发现有时你需要提供类似于下面的完整对象类型:

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
MsgBox(e.KeyCode.ToString()) 'Message what the keycode
If (e.KeyCode = Keys.A) Then
    MsgBox("e.KeyCode = Keys.A") 'Message that I've found the A
    TextBox1.AppendText("C, ")
    PictureBox2.Visible = True
    My.Computer.Audio.Play(My.Resources.C, AudioPlayMode.Background)
End If

End Sub

您是否也尝试在类似于下面的表单上的文本框中进行测试(示例中的文本框名为TextBoxKeyTest)?

    Private Sub TextBoxKeyTest_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBoxKeyTest.KeyDown
    MsgBox(e.KeyCode.ToString())'Message what the keycode
    If (e.KeyCode = Keys.A) Then
        MsgBox("e.KeyCode = Keys.A")'Message that I've found the A
        TextBox1.AppendText("C, ")
        PictureBox2.Visible = True
        My.Computer.Audio.Play(My.Resources.C, AudioPlayMode.Background)
    End If
End Sub

答案 3 :(得分:0)

这应该适用于VB 2010

Private Sub cmdWiden_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        If e.KeyCode = Keys.Up Then Me.Top = Me.Top - 5
        If e.KeyCode = Keys.Down Then Me.Top = Me.Top + 5
        If e.KeyCode = Keys.Left Then Me.Left = Me.Left - 5
        If e.KeyCode = Keys.Right Then Me.Left = Me.Left + 5
End Sub