Get KeyCode value in the KeyPress event

前端 未结 2 1061
误落风尘
误落风尘 2021-01-28 01:34

How to fix this error:

\'System.Windows.Forms.KeyPressEventArgs\' does not contain a definition for \'KeyCode\' and no extension method \'KeyCode\' acce

相关标签:
2条回答
  • 2021-01-28 02:02

    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);
        }
    
    0 讨论(0)
  • 2021-01-28 02:13

    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 ");
         }
    }
    
    0 讨论(0)
提交回复
热议问题