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?
Asked
Active
Viewed 2,395 times
-10
-
What have U tried so far? – Rajesh Jan 07 '15 at 09:42
-
1Use `Form.FormClosing` - http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing(v=vs.110).aspx – Kami Jan 07 '15 at 09:45
2 Answers
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
-
1
-
Yes, fine, but don't you think that this answer misses the most important part? – Steve Jan 07 '15 at 09:43
-
@Ali Sepehri.Kh but how to generate that alert which contain OK & CANCEL button – Manish Pant Jan 07 '15 at 09:47
-
-
1
-
1@AliSepehri.Kh its great help done by you, i am working on this from last 5 hours and getting nothing. Thank you soo much dude :) – Manish Pant Jan 07 '15 at 10:00
-
1Remember that cancelEventArgs contains also the reason for the closing event. Sometimes is not very advisable to deny a system shutdown request. – Steve Jan 07 '15 at 10:22
-
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