Microsoft KB Archive/326442

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

Article ID: 326442

Article Last Modified on 2/12/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005 Express Edition
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



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
 Create a new Visual Basic Windows Application project. By default, Form1 is created. Drag a TextBox control from the toolbox to the form. On the View menu, click Code.  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  On the Debug menu, click Start. Notice that the text box displays &quot;Textbox1&quot;.</li> 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.</li> 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.</li></ol>

<div class="references_section">