Dimitry Abramiani
Dimitry Abramiani

Reputation: 13

KeyEventArgs in C#

I have a problem to how to catch which key is pressed. This is my code, but i cant get what key was pressed. I'm using KeyEventArgs for declaration of new variable and then comparing it.

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        KeyEventArgs k = null;
        if (e is KeyEventArgs)
        {
            k = (KeyEventArgs)e;
        }

        if (k.KeyCode == Keys.Enter)
        {
            // do something here
        }


    }

Upvotes: 0

Views: 6968

Answers (2)

fatihk
fatihk

Reputation: 7919

You need to add:

 [component_name].KeyDown += new System.Windows.Forms.KeyEventHandler(this.Key_Pressed_Method);

into the constructor of your Form. Then, you can define what you want to do in Key_Pressed_Method() method.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190897

TextChanged won't give you a KeyEventArgs. You want KeyUp, KeyDown or KeyPress instead. KeyPress gives you KeyPressEventArgs instead.

Upvotes: 3

Related Questions