Control.KeyDown Control.KeyDown Control.KeyDown Control.KeyDown Event

정의

컨트롤에 포커스가 있을 때 키를 누르면 발생합니다.Occurs when a key is pressed while the control has focus.

public:
 event System::Windows::Forms::KeyEventHandler ^ KeyDown;
public event System.Windows.Forms.KeyEventHandler KeyDown;
member this.KeyDown : System.Windows.Forms.KeyEventHandler 
Public Custom Event KeyDown As KeyEventHandler 

예제

다음 코드 예제에서는 KeyDown 컨트롤에 입력 한 문자의 형식을 확인 하는 이벤트입니다.The following code example uses the KeyDown event to determine the type of character entered into the control.

   // 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;
      }
   }
// 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;
    }
}

' 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

다음 코드 예제는 발생 순서를 보여 합니다 KeyDown, KeyUp, KeyPress 이벤트 및 이벤트 처리기에 등록 하는 방법입니다.The following code example demonstrates the order of raising the KeyDown, KeyUp, KeyPress events, and how to register event handlers on them.

public partial class Form2 : Form
{
	public Form2()
	{
		InitializeComponent();
		textBox2.Multiline = true;
		textBox2.ScrollBars = ScrollBars.Both;

		//Setup events that listens on keypress
		textBox1.KeyDown += TextBox1_KeyDown;
		textBox1.KeyPress += TextBox1_KeyPress;
		textBox1.KeyUp += TextBox1_KeyUp;
	}

	// Handle the KeyUp event to print the type of character entered into the control.
	private void TextBox1_KeyUp(object sender, KeyEventArgs e)
	{
		textBox2.AppendText( $"KeyUp code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + "\r\n");
	}

	// Handle the KeyPress event to print the type of character entered into the control.
	private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
	{
		textBox2.AppendText( $"KeyPress keychar: {e.KeyChar}" + "\r\n");
	}

	// Handle the KeyDown event to print the type of character entered into the control.
	private void TextBox1_KeyDown(object sender, KeyEventArgs e)
	{
		textBox2.AppendText( $"KeyDown code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + "\r\n");
	}
}
Public Class Form2

    ' Handle the KeyDown event to print the type of character entered into the control.
    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
        TextBox2.AppendText($"KeyDown code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + vbCrLf)
    End Sub

    ' Handle the KeyPress event to print the type of character entered into the control.
    Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
        TextBox2.AppendText($"KeyPress keychar: {e.KeyChar}" + vbCrLf)
    End Sub

    ' Handle the KeyUp event to print the type of character entered into the control.
    Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
        TextBox2.AppendText($"KeyUp code: {e.KeyCode}, value: {e.KeyValue}, modifiers: {e.Modifiers}" + vbCrLf)
    End Sub

End Class

설명

키 이벤트가 다음 순서 대로 발생합니다.Key events occur in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

만 폼 수준에서 키보드 이벤트를 처리 하 고 키보드 이벤트를 수신할 다른 컨트롤에서는 설정 합니다 KeyPressEventArgs.Handled 폼의 속성 KeyPress 이벤트 처리 메서드를 true입니다.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. 컨트롤에서 탭, 리턴, ESC 키를 및 화살표 키와 같은 특정 키를 자동으로 처리 됩니다.Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically. 이러한 키에 KeyDown 재정의 해야 이벤트는 IsInputKey 양식의 각 컨트롤의 메서드.To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. 재정의 위한 코드를 IsInputKey 특수 키 중 하나를 누를 경우 확인 하 고 값을 반환 해야 true합니다.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. 재정의 하는 대신 합니다 IsInputKey 메서드를 처리할 수 있습니다 합니다 PreviewKeyDown 이벤트 집합과 IsInputKey 속성을 true합니다.Instead of overriding the IsInputKey method, you can handle the PreviewKeyDown event and set the IsInputKey property to true. 코드 예제를 참조 하세요.를 PreviewKeyDown 이벤트입니다.For a code example, see the PreviewKeyDown event.

이벤트 처리에 대한 자세한 내용은 이벤트 처리 및 발생 을 참조하십시오.For more information about handling events, see Handling and Raising Events.

적용 대상

추가 정보