tags:

views:

456

answers:

5

Is there a way to start a method in C# if a key is pressed? For example, "Esc"?

A: 

Are you writing a Console application, a WinForms application or something else? Are you trying to capture the ESC key at all times (regardless of the focused window/application) or something else?

More context required.

If you're writing a Console app, then you should start looking at things like Console.ReadKey...

http://msdn.microsoft.com/en-us/library/system.console.readkey.aspx

Martin Peck
I am writing WinForms application. User fills the text box and If he wants to delete everything, he just clicks esc key on keyboard
raimis
+5  A: 

use the OnKeyPress Event of your textbox and in the event

if(e.KeyCode==Keys.Escape)
{
    yourTextBox.Text = string.Empty;
}
Gregoire
funny, this doesn't seem to be working at all, and it's got five up votes? `private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) {...`This works. But e.KeyChar is a character type, Keys.Escape isn't and the == operator can't be applied.
Peter Perháč
@MasterPeter indeed, it was KeyCode...
Gregoire
A: 

I am writing WinForms application. User fills the text box and If he wants to delete everything, he just clicks esc key on keyboard

I think you need to handle the KeyDown event.

ChrisW
A: 

For the winforms use the appropriate Event as said by others

Raghav Bali
+1  A: 

As others have mentioned, handle the KeyDown or KeyUp event of the appropriate control. The KeyPress event would work for the Escape key as well, though it will not trigger for some keys, such as Shift, Ctrl, or ALt.

If you want to execute this function anytime the user presses the Escape key, then you probably want to handle the event on the Form. If you do this, you will probably also want to set the Form's KeyPreview property to true. This will allow the Form control to receive the event even if the focus is currently inside of one of the child controls.

If you want the behavior to be specific to a control, such as clearing the text within a textbox that currently has focus, then you should handle the KeyDown or KeyUp event of the TextBox control. This way, your event handler will not be triggered if the user presses the escape key outside of the textbox.

In some situations you might want to prevent child controls from handling the same event that you've just handled. You can use the SuppressKeyPress property on the KeyEventArgs class to control this behavior:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            MessageBox.Show("Escape key pressed");

            // prevent child controls from handling this event as well
            e.SuppressKeyPress = true;
        }
    }
Dr. Wily's Apprentice