alexander
alexander

Reputation: 89

How do I catch KeyUp event ? (sample of code, please)

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.

Upvotes: 5

Views: 10974

Answers (3)

Dave D
Dave D

Reputation: 8972

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
    }
}

Upvotes: 0

Hiber
Hiber

Reputation: 474

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

Upvotes: 0

Tom Vervoort
Tom Vervoort

Reputation: 5108

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;
            //...
    }
}

Upvotes: 7

Related Questions