Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Close Application at Press of Escape Button

0.00/5 (No votes)
1 Jul 2011 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here