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?
views:
237answers:
4The 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 :)
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
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.