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:
- Open the project, click on any empty area on the form.
- Ensure that Form is selected not a control if present on your Form.
- In the Properties Window, click on the Lightening icon to open events for the Form.
- Double click on KeyUP and KeyDown events to create event methods for these two.
- 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)
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
i use this code but don’t work….