Control::PreviewKeyDown Event


Occurs before the KeyDown event when a key is pressed while focus is on this control.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

event PreviewKeyDownEventHandler^ PreviewKeyDown {
	void add(PreviewKeyDownEventHandler^ value);
	void remove(PreviewKeyDownEventHandler^ value);

Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses. For example, by default, a Button control ignores the arrow keys. Pressing the arrow keys typically causes the focus to move to the previous or next control. The arrow keys are considered navigation keys and pressing these keys typically do not raise the KeyDown event for aButton. However, pressing the arrow keys for a Button does raise the PreviewKeyDown event. By handling the PreviewKeyDown event for a Button and setting the IsInputKey property to true, you can raise the KeyDown event when the arrow keys are pressed. However, if you handle the arrow keys, the focus will no longer move to the previous or next control.

For more information about handling events, see Handling and Raising Events.

The following code example demonstrates a Button that includes a ContextMenuStrip. When the Button has the focus and you press the UP ARROW or DOWN ARROW keys, the ContextMenuStrip appears. The PreviewKeyDown event handler detects when the UP ARROW or DOWN ARROW keys are pressed and sets the IsInputKey property to true. This raises the KeyDown event so that you can display the ContextMenuStrip. You should not put any logic in the PreviewKeyDown event handler, other than to set the IsInputKey property. Instead, you should put your logic in the KeyDown event handler.

No code example is currently available or this language may not be supported.

.NET Framework
Available since 2.0
Return to top