-10

I wanted that when user closes the window in (Window Form Application, C#) by clicking (X) or pressing ESC key or by pressing ALT+F4, an alert will show i.e a Dialog(containing two buttons OK & CANCEL). How to do?

Kurubaran
  • 8,696
  • 5
  • 43
  • 65

2 Answers2

1

You can find this by a simple search!

Handle Closing event of your form:

this.Closing += OnClosing; // For example put this in the constructor of your form

private void OnClosing(object sender, CancelEventArgs cancelEventArgs)
{
        string msg = "Do you want to close this?";
        DialogResult result = MessageBox.Show(msg, "Close Confirmation",
            MessageBoxButtons.YesNo/*Cancel*/, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
            /* Do something */;
        else if (result == DialogResult.No)
            cancelEventArgs.Cancel = false;

}
Ali Sepehri.Kh
  • 2,468
  • 2
  • 18
  • 27
0

you could do this at application level

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ApplicationExit += Application_ApplicationExit;
        AppDomain.CurrentDomain.ProcessExit += Application_ApplicationExit;
        Application.Run(new Form1());
    }
    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        //Do something
    }
Mitz
  • 561
  • 8
  • 21