VB.Net - Keydown event not firing with WinForm application
Arrow keys do not raise KeyDown in a WinForm because the form swallows them. Override ProcessCmdKey to catch them.
I needed to capture arrow key presses in a Windows Forms application, but the key events never fired for them. Setting KeyPreview did not help. Arrow keys are special keys, and the controls on the form intercept them before the form sees them.
The fix is to override ProcessCmdKey on the form.
Example
Add a PictureBox to the form and give it a background colour. Pressing an arrow key moves it around the form.
vb
Public Class Form1
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keydata As Keys) As Boolean
If keydata = Keys.Right Then
PictureBox1.Left += 10
End If
If keydata = Keys.Left Then
PictureBox1.Left -= 10
End If
If keydata = Keys.Up Then
PictureBox1.Top -= 10
End If
If keydata = Keys.Down Then
PictureBox1.Top += 10
End If
If keydata = Keys.Right Or keydata = Keys.Left Or keydata = Keys.Up Or keydata = Keys.Down Then
OnKeyDown(New KeyEventArgs(keydata))
ProcessCmdKey = True
Else
ProcessCmdKey = MyBase.ProcessCmdKey(msg, keydata)
End If
End Function
End Class
For the arrow keys the code raises KeyDown itself and returns True, so the key is treated as handled. Every other key goes to the base implementation.