Setting e.Handled in the KeyDown event has no effect in Visual Basic .NET or in Visual Basic 2005 (326442)



The information in this article applies to:

  • Microsoft Visual Basic 2005 Express Edition
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q326442

SYMPTOMS

When you handle the KeyDown event in a Windows Form control, alphanumeric keystrokes are still processed after you set the e.Handled argument to True.

CAUSE

The KeyDown event is not designed to handle alphanumeric keystrokes. Although the KeyDown event fires when an alphanumeric key is pressed, you can only use the KeyDown event to determine information about what key was pressed. This event does not stop an alphanumeric keystroke from being processed.

Non-alphanumeric keystrokes (such as the arrow keys, the HOME key, the END key, and the DELETE key) can be handled during the KeyDown event.

RESOLUTION

To resolve this problem, use the KeyPress event instead of the KeyDown event if you have to handle alphanumeric keystrokes.

STATUS

This behavior is by design.

MORE INFORMATION

The KeyDown event reports the exact physical state of a key itself. In contrast, the KeyPress event does not report the state of the keyboard directly. The KeyPress event does not recognize the up or the down state of the key; it supplies the character that the key represents.

Steps to Reproduce the Behavior

  1. Create a new Visual Basic Windows Application project. By default, Form1 is created.
  2. Drag a TextBox control from the toolbox to the form.
  3. On the View menu, click Code.
  4. Add the following code to the Form1 class module:
    Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
       e.Handled = True
    End Sub
    					
  5. On the Debug menu, click Start. Notice that the text box displays "Textbox1".
  6. Press a non-alphanumeric key, such as one of the arrow keys. Notice that the keystroke is handled and is not processed by the control.
  7. Use alphanumeric keys to type text in the textbox. Notice that these keystrokes are still processed and are displayed in the control even though e.Handled was set to True in the KeyDown event.

REFERENCES

For additional information, click the article number below to view the article in the Microsoft Knowledge Base:

320583 HOW TO: Trap Keystrokes in .NET Controls by Using Visual Basic .NET


Modification Type:MajorLast Reviewed:2/8/2006
Keywords:kbtshoot kbvs2005applies kbvs2005swept kbprb KB326442