How to fix this error:
\'System.Windows.Forms.KeyPressEventArgs\' does not contain a definition for \'KeyCode\' and no extension method \'KeyCode\' acce
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);
}
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 ");
}
}