Tal Stol
Tal Stol

Reputation:

.NET, and "know" when a keyboard button is being pressed

I'm making a program in C#, And I want to know when the user is pressing\pressed a keyboard button (for now: 1-9 buttons on keyboard).
How can I do it?

Upvotes: 0

Views: 1013

Answers (4)

Khadaji
Khadaji

Reputation: 2167

Don't forget to set the KeyPreview property to true, else other controls on your form (if you have other controls on your form) will receive the event (if they have focus) before the form gets it.

Upvotes: 2

Thorarin
Thorarin

Reputation: 48496

The Control.KeyPress event (and related KeyDown and KeyUp) should do what you need. Just define an event handler for the one you need in your form:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    MessageBox.Show("Key pressed: " + e.KeyChar);
}

The MSDN page under the link has a more extensive example that deals with "special" keys (you will need to use KeyPress or KeyDown for those).

If you want to capture keys while the focus is not on your form, that's a different matter entirely, but I don't think that's the case as you want to capture keys 1-9. Not the typical global hotkey :)

Upvotes: 4

Camal
Camal

Reputation: 4314

What you search are the 2 Events KeyDown and KeyUp.

KeyUp is when a Key "was" pressed and the user lift his finger up. KeyDown is the other event.

Just take a new Form. Go to the Events(Press F4) and you will find KeyDown and Up.

    private void maskedTextBox1_KeyDown_1(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)

and so on :D

Upvotes: 0

RvdK
RvdK

Reputation: 19800

Hook an function to the OnKeyUp event of a form. see here

private void form1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if ((e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9) || (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9))

    {
        //Do something
    }
}

Upvotes: 0

Related Questions