2011-08-27 185 views
0

我正试图在Visual Basic(VS 2010)中编写一个程序来响应箭头键。我知道在Java中有关键的监听器,但不知道在VB中是否存在这样的事情以及如何对它进行编码。请给我看一些例子。 谢谢。Visual Basic密钥监听器

+1

console?的WinForms? WPF? XNA? –

回答

2

如果您正在执行winforms,请将表单的KeyPreview属性设置为true,然后设置KeyDown事件。您的代码将如下所示:

Dim previousKey As Keys? = Nothing 

Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown 
    If e.KeyCode = Keys.Up Then 
     'up arrow 
    End If 


    If e.KeyCode = Keys.Left Then 
     'left arrow 
     If Not previousKey Is Nothing And previousKey = Keys.Up Then 
      'Up arrow and then Left Arrow 
      MessageBox.Show("there, that's better") 
     End If 
    End If 

    If e.KeyCode = Keys.Right Then 
     'right arrow 
    End If 

    If e.KeyCode = Keys.Down Then 
     'down arrow 
    End If 

    'After everything is done set the current key as the previous key. 
    previousKey = e.KeyCode 
End Sub 
+0

非常感谢。这就是我想要的。 – yihangho

+0

好的。现在,当按下2个键时,程序是否可以响应?就像按向上箭头键和向左箭头键时? – yihangho

+0

我修改了我的示例以捕获向上箭头,然后向左箭头。 –