tags:

views:

57

answers:

4

Hello guys,

I need to catch KeyDown & especially KeyUp events for 1,2,3,4,5,6,7,8,9 keyboard buttons.

How does it do ? I can catch KeyDown event but what about KeyUp ? Please, provide some simple code.

.net 2.0, winforms (not wpf)

A: 

in this article provided how to create custom control and code sample.

loviji
+2  A: 
private void Form1_Load(object sender, EventArgs e)
{
    this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}

void Form1_KeyUp(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.NumPad1:
            break;
        case Keys.NumPad2:
            break;
            //...
    }
}
Tom Vervoort
Don't forget to enable KeyPreview
PoweRoy
A: 

private void Form1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyData == Keys.D1) // number 1 { MessageBox.Show("Hello"); } }

Hiber
A: 

If you need the logic to be exactly the same then you can hook up the same event handler to both the KeyUp and KeyDown events of the control you want to capture input on.

// this occurs as part of Initialisation via the designer or you can hook up manually
myControl.KeyDown += myControl_KeyChange;
myControl.KeyUp += myControl_KeyChange;
// ...

private void myControl_KeyChange(object sender, KeyEventArgs e)
{
    switch( e.KeyCode )
    {
        case Keys.1:
        {
            // handle the 1 key being pressed
            break;
        }        
        case Keys.2:
        {
            // handle the 2 key being pressed
            break;
        }
        // etc
    }
}
Dave