Detect Escape on keyPress

Viewed 158

I want to detect Escape on a field in C# to add '_', I test this following code e.KeyCode == Keys.Escape but not working. Have you an idea ?

        private void tbxLibelle_KeyPress(object sender, KeyPressEventArgs e)
        {
            
            if (e.KeyCode == Keys.Escape)
            {
                tbxNomimage.Text += '_';
            }
            else
            {
                tbxNomimage.Text = tbxLibelle.Text;
            }
        }

1 Answers

You can't get KeyCode from KeyPress event, KeyPressEventArgs provide only the KeyChar property. KeyCode can get from the KeyDown event. System.Windows.Forms.KeyEventArgs has the required KeyCode property:

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Escape)
            {
                tbxNomimage.Text += '_';
            }
            else
            {
                tbxNomimage.Text = tbxLibelle.Text;
            }
        }

If the KeyDown event is not suit, you can save the KeyCode in global private field.

        private Keys key_Code;
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.key_Code == Keys.Escape)
            {
                tbxNomimage.Text += '_';
            }
            else
            {
                tbxNomimage.Text = tbxLibelle.Text;
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            this.key_Code = e.KeyCode;
        }

Key events occur in the following order:

  • KeyDown
  • KeyPress
  • KeyUp

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress?view=windowsdesktop-6.0

Related