views:

237

answers:

4

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?

+4  A: 

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 :)

Thorarin
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(VS.80).aspx
PoweRoy
1-9 are character keys however, which is what he was asking for.
Thorarin
my bad, 1-9 seemed to me non character keys
PoweRoy
A: 

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
    }
}
PoweRoy
A: 

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

Camal
+2  A: 

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.

Khadaji
+1: Very, very important.
Callum Rogers