How To Ideas | How To Articles | How To Tutorials


2

How To Check If A Key Is Pressed In C#


While developing applications in which you want your user to press some key and your application will do some work for your user, you need to detect if a key is pressed or released. In this article, I will show you how can you achieve that.

Instructions:

  1. Open the project, click on any empty area on the form.
  2. Ensure that Form is selected not a control if present on your Form.
  3. In the Properties Window, click on the Lightening icon to open events for the Form.
  4. Double click on KeyUP and KeyDown events to create event methods for these two.
    image
  5. Use the following code to detect if required key is pressed. // This Event will occurs when a key is pressed
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {           
    if (e.KeyCode == Keys.Up)           
    {
    // Write your code for this key           
    }
    if (e.KeyCode == Keys.Down)
    {
          // Write your code for this key
    }
    }

    // This Event will occurs when a key is released
    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
    if (e.KeyCode == Keys.Up)
    {
          // Write your code for this key
    }
    if (e.KeyCode == Keys.Down)
    {
          // Write your code for this key
    }
    }

Incoming search terms:

  • c# checkkeys (1)
  • check if any key has been pressed c# (1)
  • detect text name of button pressed with c# (1)
Filed in: C# Tags: , , , , , , , , , , , , , , , , , , , , , , ,

2 Responses to "How To Check If A Key Is Pressed In C#"

  1. noName says:

    Hello. I want to do something while a specific key is hold pressed and do something else when it is released. Any idea how can i do this?.. TY

  2. mahdi says:

    i use this code but don’t work….

Leave a Reply

Submit Comment



© 0944 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.