Problem Description: When a new form is added, the KeyDown event is processed normally, but when a control is added, such as Button,textbox, the KeyDown event of the form is not triggered and the handler for the KeyDown event is not invoked.
Cause: Because the control is added to the form, the focus is on one of the controls, and if the event form that we want to handle and the control that gets the focus are both owned, the system will pass the keyboard's action key value directly to the control that gets the focus. , this problem will arise.
Solution: You need to set the KeyPreview property of the form to true to pass the system's incoming key value to the form before passing it to the control. MSDN Instructions for KeyPreview: 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. For more information, see MSDN:
Http://msdn.microsoft.com/zh-cn/library/system.windows.forms.form.keypreview (vs.80). aspx
Problem two description: Set the KeyPreview value to true after pressing the function keys and the number keys are not the problem, but by the arrow key still does not trigger the KeyDown event.
Cause: The key is handled as a system key, and the default arrow key is to move the focus, the system does not pass the key value of the keyboard to a form or control that gets the focus, and does not trigger the KeyDown event of the form. No other control can move the focus when there is no control, and the system does not process it, which will pass the key value to the form, triggering the KeyDown event
Solution: Override the default System key processing mode, and encounter the direction key, then return directly, the system does not process, so that the key value will be passed to the form, triggering the KeyDown event.
Override the default code for System key handling:
protected override bool processDialogKey (Keys keyData)
{
Switch (keyData)
{
Case Keys.Tab:label1. Text = "1";
Break
Case Keys.Left:label1. Text = "2";
Break
Case Keys.Right:label1. Text = "3";
Break
}
if (KeyData = = Keys.up | | keyData = Keys.down | |
KeyData = = Keys.left | | keydata== keys.right)
return false;
Else
Returnbase. processDialogKey (KeyData);
}
Transferred from: http://blog.csdn.net/genganpeng/article/details/8649191
C # Forms cannot accept KeyDown events