Keyboard event detection in C#

Joined
Feb 8, 2023
Messages
1
Reaction score
0
Hello Guys, I am trying to make an application in C# which needs to detect if user touched keyboard on any key. I do not care which key was pressed, I only need to know that it was pressed so my software pause its activity for some time while keyboard is in use.
I learnt that it is easy to see if key modifiers were used just simply doing

if (ModifierKeys != 0) { Ticks = 0; } //resetting timer for inactivity if modifier key is pressed

but I can not find anything this simple for detecting all keys with only a couple lines of code. Maybe a better way is intercepting interrupt from keyboard if this is possible?

Could someone help please?
 
Joined
Jan 30, 2023
Messages
107
Reaction score
13
Yes, you can detect if a key is pressed in C# using the KeyDown event of the Form class.

Like this :
C#:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        KeyPreview = true;
        KeyDown += Form1_KeyDown;
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        // Do something when any key is pressed
    }
}

This will capture the KeyDown event for the entire form, so you'll be notified whenever any key is pressed, regardless of which control has focus.

You can also use the PreviewKeyDown event instead of KeyDown if you want to handle the event before it's passed on to other controls on the form.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top