If you are using Windows Forms, add this in the constructor:
Me.KeyPreview = True
And then create this method:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.Up
Exit Select
Case Keys.Down
Exit Select
Case Keys.Left
Exit Select
Case Keys.Right
Exit Select
End Select
End Sub
Setting
KeyPreview
to
True
makes sure that the
Form1_KeyDown
will always be called if a key is pressed, even if the focus is on another control, such as a
TextBox
.
If you are using WPF:
Private Sub MainWindow_PreviewKeyDown(sender As Object, e As KeyEventArgs) Handles Me.PreviewKeyDown
Select Case e.Key
Case Key.Up
Exit Select
Case Key.Down
Exit Select
Case Key.Left
Exit Select
Case Key.Right
Exit Select
End Select
End Sub
In WPF, the
PreviewKeyDown
event has the same purpose as the
KeyPreview
property in Windows Forms. If you don't want that, just use
KeyDown
.
If you are using a Console Application:
Dim c As ConsoleKeyInfo = Console.ReadKey()
Select Case c.Key
Case ConsoleKey.UpArrow
Exit Select
Case ConsoleKey.DownArrow
Exit Select
Case ConsoleKey.LeftArrow
Exit Select
Case ConsoleKey.RightArrow
Exit Select
End Select
Note that this will only work if you have called
Console.ReadKey()
.