Sometimes there is a need to respond to a form's key message when writing a form application using the. Net framework.
When there are no other controls on the form, the form can respond directly to those messages.
However, when there are other controls on the form, it is discovered that the form will no longer respond to these messages because the messages are processed by the controls on them and are not sent to the parent form.
However, it is necessary to respond to the key message on the form, and after exploring it, it is found that the form class has a KeyPreview property that allows it to receive key messages. It is defined as follows:
Properties of the KeyPreview
Gets or sets a value that indicates whether the form will receive this key event before the key event is passed to the control that has the focus.
Namespaces: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
Grammar
True if the form will receive all key events, or False if the currently selected control on the form receives a key event. The default is False. Note
When this property is set to True, the form receives all KeyPress, KeyDown, and KeyUp events. After the form's event handler finishes processing the keystroke, it then assigns the keystroke to the control that has the focus. For example, if the KeyPreview property is set to True and the currently selected control is a TextBox, the TextBox control receives the pressed key after the form's event handler has processed the keystroke. To handle keyboard events at the form level only and not allow the control to receive keyboard events, set the Keypresseventargs.handled property in the form's KeyPress event handler to True.
You can use this property to handle most keystroke events in your application, and you can handle keystroke events or invoke the appropriate controls to handle keystroke events. For example, when your application uses function keys, you might want to process these keystrokes at the form level instead of writing code for each control that might receive a keystroke event.
Attention |
If the form has no visible or enabled controls, the form automatically receives all keyboard events. |
Attention |
A control on a form can be programmed to cancel any keystrokes it receives. Because controls never send these keystrokes to a form, the form will never see them regardless of the KeyPreview settings. |
Form.keypreview Property 2