user4901961
user4901961

Reputation:

Does not contain definition for Key

I am new at coding, sorry if this is not proper. I was trying in C# to recognize if I am holding the Space key down. I found this code online, but it is not working.

if (e.Key == Key.Space)
  {

  }

The error I am getting is:

'EventArgs' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'EventArgs' could be found (are you missing a using directive or an assembly reference?)

Any help would be appreciated.

Upvotes: 0

Views: 3268

Answers (3)

jned29
jned29

Reputation: 478

In what object? You have to assign events on your object. Sample if you're using textbox, go to the property and assign events like Keydownon key section. (i.e. Textbox1_KeyDown) double click on it to see the code then insert your key event arguments.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        MessageBox.Show("Space pressed");
    }
}

You can also use KeyCode e.KeyCode == Key.Space

Upvotes: 1

Arphile
Arphile

Reputation: 861

KeyEventArgs contains e.Key.

Change your EventHandler as KeyEventHandler and use KeyEventArgs instead of EventArgs

Sample Code:

public void EventAdder() {
    Child.KeyDown += new KeyEventHandler( OnKeyDown );
}

private void OnKeyDown( object sender, KeyEventArgs e )
{
    switch( e.KeyCode )
    {
        case Keys.Escape:
            Btn_Cancel_Click( sender, e );
            break;
        case Keys.Enter:
            Btn_Commit_Click( sender, e );
            break;
    }
}

Upvotes: 5

jkosmala
jkosmala

Reputation: 94

EventArgs is base class for events, you have to cast it on specific type. In this case KeyEventArgs. You will notice that in many other cases.

Upvotes: 0

Related Questions