Home > VB.Net > VB.Net – Keydown event not firing with WinForm application

VB.Net – Keydown event not firing with WinForm application

As part of my recent project I was handed with a job to create a windows form application. In this application I had to capture arrow key events. For my surprise the key event where not firing for arrow keys. I tried setting “KeyPreview” but that didn’t helped. Then I realized these are special keys and controls in the form will intercept these.

The solution was to override ProcessCmdKeys function as below

For demonstration, add a PictureBox control and change its background color. Pressing arrow key will move it around the form

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
Advertisements
Categories: VB.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: