Click to See Complete Forum and Search --> : Using arrow keys


Steve Putt
August 8th, 2002, 02:51 PM
Another rookie question...
I want to use the arrow keys to execute some code in my form. I've been all through "Help", which is no help at all. I've found KeyPress (says it doesn't work with arrows) and KeyDown, but I can't figure out what arguments to use, and I also can't find the key codes in Object Browser.
For a "Private Sub Form_KeyDown(keycode As Integer, shift As Integer)", what form is the keycode? Do I just use the 37, 38, 39, and 40 integer values for the arrow keys?
My form is filled with 150 picture boxes (created at runtime). I want the keydown to work regardless of the focus. Help says "If the KeyPreview property is set to True, a form receives these events before controls.... Use the KeyPreview property to create global keyboard-handling routines." Can I put a KeyPreview in the frmMain_Load sub (my form is named frmMain), and what will it look like?

DSJ
August 8th, 2002, 03:25 PM
Add this to your form class code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub
Private Shadows Sub KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyCode
Case Keys.Left
MsgBox("Arrow Left")
Case Keys.Right
MsgBox("Arrow Right")
Case Keys.Up
MsgBox("Arrow Up")
Case Keys.Down
MsgBox("Arrow Down")
Case Else
'nothing
End Select
End Sub