English 中文(简体)
Press Escape key to call method
原标题:

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

最佳回答

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

I think you need to handle the KeyDown event.

问题回答

use the OnKeyPress Event of your textbox and in the event

if(e.KeyCode==Keys.Escape)
{
    yourTextBox.Text = string.Empty;
}

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;
    }
}

In case someone is looking for how to do this in a console application

if (Console.ReadKey().Key == ConsoleKey.Escape)
{
    return;
}

You have to switch the form property "KeyPreview" to true or your events will not be fired. Handling these events alone will not do anything even though the events are correct. It will look to you like nothing really happens even though you have subscribed the proper event handlers.

First in Properties do > KeyPreview : True

Then :

private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape)
        {
            //call your method here
        }
    }

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

The basic answer is listed here several time

Implement Form_KeyDown

Private Sub frmCustomerSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        Try
            If e.KeyCode = Keys.Escape Then

                ClearFindForm()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

End Sub

Set form.keyPreview

form.KeyPreview = true

The additional thing you need to check is whether you have a button capturing ESC so it can be the form.cancelButton

to be sure ...

form.CancelButton = nothing

This is sneaky. If you have set that and forgot about it, the Escape key will not trigger the KeyDown event.

I was led to this because a button set to be the form.CancelButton does not seem to fire if it is invisible or on a non visible tab,so KEYDOWN is your only option.

With Event KeyPress...

   //Escape 
   if (e.KeyChar ==   )
   {
            this.DialogResult = DialogResult.Cancel;
            e.Handled = true;
   }

You can use KeyUp event too. I prefer it though.

private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) {
     if (e.Key == Key.Escape) {
         //WHAT WILL HAPPEN INSERT HERE
     }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签