views:

685

answers:

2

The key up event gets triggered when a key is released. This holds true for normal keys like a, b etc. However, holding down the arrow key or escape key produses different results. Instead of firing a key up event when the key is released, it gets fired soon after the key down event. So, holding down a arrow key becomes equal to pressing and releasing the key many times very fast. Any explaination and work around to determine when the key is actually released?

+3  A: 

The KeyUp event isn't actually fired (for all keys not just arrow keys etc.) until you release the key, there are just many repeated KeyDown events. At least, that's the way it looks to me from some test code.

My workaround is to disable the KeyDown handler after a KeyDown event is detected using

RemoveHandler Me.KeyDown, AddressOf Form1_KeyDown

and then re-enabling when the KeyUP event is fired.

AddHandler Me.KeyDown, AddressOf Form1_KeyDown

Of course if you want to handle simultaneous multiple key presses then this won't work. You'll have to store whether or not the Key in question is already down and ignore the respective KeyDown event.

RobS
+1  A: 

I've just run into similar problem. Keyboard handler behaves weird:

If focus and handlers are in textbox:

  • When alphanumeric key is held down, I got multiple Press and Down events
  • Arrows and function keys produce multiple Down events

If handling events for a form with KeyPreview enabled, only KeyUp event for the arrow keys is handled.

It's possible to handle all keys on lower level by overriding ProcessCmdKey.

If you want to handle a left arrow key:

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
    Select Case keyData
        Case Keys.Left
            Debug.WriteLine("Left")
            Return True
        Case Else
            Return MyBase.ProcessCmdKey(msg, keyData)
    End Select
End Function
Hugo Riley