Smygolas
Smygolas

Reputation: 45

Get KeyCode value in the KeyPress event

How to fix this error:

'System.Windows.Forms.KeyPressEventArgs' does not contain a definition for 'KeyCode' and no extension method 'KeyCode' accepting a first argument of type 'System.Windows.Forms.KeyPressEventArgs' could be found (are you missing a using directive or an assembly reference?)

Code:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         MessageBox.Show("Enter Key Pressed ");
     }
}

I'm using Visual studio 2010, framework 4 for this project.

Upvotes: 1

Views: 24662

Answers (2)

Gonen09
Gonen09

Reputation: 119

try this

    private void game_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
            MessageBox.Show(Keys.Enter.ToString(), "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

Upvotes: 0

Eugene Podskal
Eugene Podskal

Reputation: 10401

You can't get KeyCode from KeyPress(at least without using some mapping) event because KeyPressEventArgs provide only the KeyChar property.

But you can get it from the KeyDown event. System.Windows.Forms.KeyEventArgs has the required KeyCode property:

    private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
       MessageBox.Show(e.KeyCode.ToString());
    }

If the KeyDown event doesn't suit you, you can still save the KeyCode in some private field and use it later in the KeyPress event, because under normal circumstances each KeyPress is preceeded by KeyDown:

Key events occur in the following order:

  • KeyDown

  • KeyPress

  • KeyUp

private Keys m_keyCode;

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    this.m_keyCode = e.KeyCode;
}

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (this.m_keyCode == Keys.Enter)
     {
         MessageBox.Show("Enter Key Pressed ");
     }
}

Upvotes: 8

Related Questions