Key Press on Form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Karl Raams
    New Member
    • Jul 2011
    • 8

    Key Press on Form

    Hi,

    I have this form that has all these controls on it such as buttons, entry fields, lists, and combo boxes, and I've been looking around the net for a while now trying to find a way to track key presses on my form so that I can trigger a set of code. For example when the user presses Shift + W call code that moves picture box up. I have the KeyPreview set to True on the form and I have placed this code.

    Code:
        Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
            If e.KeyCode = Keys.Shift And e.KeyCode = Keys.W Then
                MovePictureUp()
                lblMessage.Text = "Moved"
            End If
        End Sub
    I'm pretty new to the Visual Basic language and can't seem to work out what I've done wrong here. Any pointers or suggestions would be greatly appreciated.

    Thanks, Karl
    Last edited by Meetee; Jul 20 '11, 05:11 AM.
  • R MacDonald
    New Member
    • Mar 2011
    • 24

    #2
    Hello, Karl,

    The problem here is that the event handler fires for each key pressed. That is, it fires once when the shift key is pressed. Then e.KeyCode is Keys.ShiftKey. Next it fires when the "W" is depressed. Then e.KeyCode is Keys.W. e.Keycode can't be both at the same time.

    Just change your If statement to read:
    If (e.KeyCode = Keys.W AndAlso e.Modifiers = Keys.Shift) Then

    and I think you will get what you expect.

    Cheers,
    Randy

    Comment

    • Karl Raams
      New Member
      • Jul 2011
      • 8

      #3
      Thanks Randy,

      It seems to be working now :)! I think I read up on the documentation of e.Modifiers to see if I can understand a bit more about what the code is doing.

      Regards, Karl

      Comment

      Working...