Click here to Skip to main content
12,253,114 members (52,071 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.7K views
1 bookmarked
Posted

Close Application at Press of Escape Button

, 1 Jul 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Your tip is useful for main forms with no close or cancel button. But most time you will want the "escape-close-form-behaviour" only with dialogs. This is the recommended way to do it: (Now i see Indivara already mentioned it in the comments)using System;using...
Your tip is useful for main forms with no close or cancel button. But most time you will want the "escape-close-form-behaviour" only with dialogs. This is the recommended way to do it: (Now i see Indivara already mentioned it in the comments)

using System;
using System.Windows.Forms;
 
namespace CloseByEscape
{
    static class Program
    {
        static void Main()
        {
            // Create a Dialog like form with an close (=cancel) button
            Form formDialog = new Form();
            Button button = new Button();
            button.Text = "Close";
            //button.DialogResult = DialogResult.Cancel; // you could also set the DialogResult for the Button
            formDialog.CancelButton = button; // Set the close button as CancelButton
            formDialog.Controls.Add(button);
            button.Click += delegate(object sender, EventArgs e)
             {
                 formDialog.Close();
             };
            Application.Run(formDialog);
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

johannesnestler
Austria Austria
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 5 I'd prefer usage of the AcceptButton... Pin
Eduard Keilholz10-Nov-11 21:25
memberEduard Keilholz10-Nov-11 21:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 1 Jul 2011
Article Copyright 2011 by johannesnestler
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid