Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 4
Control Class
Control Events
 KeyDown Event
Collapse All/Expand All Collapse All
.NET Framework Class Library
Control..::.KeyDown Event

Occurs when a key is pressed while the control has focus.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
Visual Basic
Public Event KeyDown As KeyEventHandler
C#
public event KeyEventHandler KeyDown
Visual C++
public:
 event KeyEventHandler^ KeyDown {
    void add (KeyEventHandler^ value);
    void remove (KeyEventHandler^ value);
}
F#
member KeyDown : IEvent<KeyEventHandler,
    KeyEventArgs>

Key events occur in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs..::.Handled property in your form's KeyPress event-handling method to true. Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true. Instead of overriding the IsInputKey method, you can handle the PreviewKeyDown event and set the IsInputKey property to true. For a code example, see the PreviewKeyDown event.

For more information about handling events, see Consuming Events.

The following code example uses the KeyDown event to determine the type of character entered into the control.

Visual Basic
' Boolean flag used to determine when a character other than a number is entered.
Private nonNumberEntered As Boolean = False


' Handle the KeyDown event to determine the type of character entered into the control.
Private Sub textBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _
     Handles textBox1.KeyDown
    ' Initialize the flag to false.
    nonNumberEntered = False

    ' Determine whether the keystroke is a number from the top of the keyboard.
    If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
        ' Determine whether the keystroke is a number from the keypad.
        If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
            ' Determine whether the keystroke is a backspace.
            If e.KeyCode <> Keys.Back Then
                ' A non-numerical keystroke was pressed. 
                ' Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = True
            End If
        End If
    End If
    'If shift key was pressed, it's not a number.
    If Control.ModifierKeys = Keys.Shift Then
        nonNumberEntered = true
    End If
End Sub 'textBox1_KeyDown


' This event occurs after the KeyDown event and can be used 
' to prevent characters from entering the control.
Private Sub textBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) _
    Handles textBox1.KeyPress
    ' Check for the flag being set in the KeyDown event.
    If nonNumberEntered = True Then
        ' Stop the character from being entered into the control since it is non-numerical.
        e.Handled = True
    End If
End Sub 'textBox1_KeyPress
C#
        // Boolean flag used to determine when a character other than a number is entered.
        private bool nonNumberEntered = false;

        // Handle the KeyDown event to determine the type of character entered into the control.
        private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if(e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift) {
                nonNumberEntered = true;
            }
        }

        // This event occurs after the KeyDown event and can be used to prevent
        // characters from entering the control.
        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }
        }

Visual C++
   // Boolean flag used to determine when a character other than a number is entered.
private:
   bool nonNumberEntered;

   // Handle the KeyDown event to determine the type of character entered into the control.
   void textBox1_KeyDown( Object^ /*sender*/, System::Windows::Forms::KeyEventArgs^ e )
   {
      // Initialize the flag to false.
      nonNumberEntered = false;

      // Determine whether the keystroke is a number from the top of the keyboard.
      if ( e->KeyCode < Keys::D0 || e->KeyCode > Keys::D9 )
      {
         // Determine whether the keystroke is a number from the keypad.
         if ( e->KeyCode < Keys::NumPad0 || e->KeyCode > Keys::NumPad9 )
         {
            // Determine whether the keystroke is a backspace.
            if ( e->KeyCode != Keys::Back )
            {
               // A non-numerical keystroke was pressed.
               // Set the flag to true and evaluate in KeyPress event.
               nonNumberEntered = true;
            }
         }
      }
      //If shift key was pressed, it's not a number.
      if (Control::ModifierKeys == Keys::Shift) {
         nonNumberEntered = true;
      }
   }

   // This event occurs after the KeyDown event and can be used to prevent
   // characters from entering the control.
   void textBox1_KeyPress( Object^ /*sender*/, System::Windows::Forms::KeyPressEventArgs^ e )
   {
      // Check for the flag being set in the KeyDown event.
      if ( nonNumberEntered == true )
      {         // Stop the character from being entered into the control since it is non-numerical.
         e->Handled = true;
      }
   }

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Application wide key replacement      Nico Boey   |   Edit   |   Show History
If you need an application wide key replacement, e.g. replacing the numpad decimal point with the current culture's decimal separator (yes, there are countries where the decimal separator is a comma), you need a IMessageFilter; look here for an example: http://code.msdn.microsoft.com/Replace-numpad-decimalpoint-c1e0e6cd
Tags What's this?: Add a tag
Flag as ContentBug
Redundant Code in the Example      Talha Munir   |   Edit   |   Show History
Here is a simpler solution. Just Control the input in keydown event of textbox as follows
private void txtBox1_KeyDown(object sender, KeyEventArgs e)
 {
           if (Control.ModifierKeys  == Keys.Shift)
            {
                e.SuppressKeyPress = true;
                return;
            }

            if (((e.KeyCode >= Keys.D0 &;;&;; e.KeyCode <= Keys.D9) ||
                 (e.KeyCode >= Keys.NumPad0 &;;&;; e.KeyCode <= Keys.NumPad9) ||
                  e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod ||
                  e.KeyCode == Keys.Back || e.KeyCode == Keys.Tab ||
                  e.KeyCode == Keys.Left || e.KeyCode == Keys.Right ||
                  e.KeyCode == Keys.End || e.KeyCode == Keys.Home ||
                  e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Delete))
            {
              
            }
            else if (e.KeyCode >= Keys.A || e.KeyCode <= Keys.Z)
                e.SuppressKeyPress = true;
}

Tags What's this?: Add a tag
Flag as ContentBug
Bad Example by MSDN and My Code      Chakravarthy   |   Edit   |   Show History

The given example is inappropriate for eliminating the key input. The given example doesn’t work for you, if your interest is to prevent the user to input anything other than the numbers. I’ve tried and came up with a simple workout for preventing the user to input other than numbers. Here is my code, please comment and revise if it can be more simplified.

Step 1: We need a small reusable function as mentioned below.
bool IsDigitInput(char keyValue)
{
return ((keyValue >= '0') &;;&;; (keyValue <= '9') || keyValue.Equals('\b'));
}

Step 2: Consume the above method at the KeyPress event of the text box as mentioned below
if (!IsDigitInput(e.KeyChar))
{
e.KeyChar = new char();
}

Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker