Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture ESC in textbox

Tags:

c#

.net

winforms

I want to have the Esc key undo any changes to a textbox since it got focus.

I have the text, but can't seem to figure out how to capture the Esc key. Both KeyUp and KeyPressed don't seem to get it.

like image 451
Baruch Avatar asked Dec 22 '22 04:12

Baruch


1 Answers

This should work. How are you handling the event?

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{          
    if (e.KeyCode == Keys.Escape)
    {
       MessageBox.Show("Escape Pressed");
    }
 }

Edit in reply to comment - Try overriding ProcessCmdKey instead:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
     if (keyData == Keys.Escape && myTextBox.Focused) 
     {
         MessageBox.Show("Escape Pressed");
     }

     return base.ProcessCmdKey(ref msg, keyData);
}
like image 171
keyboardP Avatar answered Dec 24 '22 02:12

keyboardP