The problem is that the messagebox with \"sure you wanna close?\" does pop up, but when I click \"no\", it still proceeds to close the program. Any suggestions? Here\'s my c
You are expected to set the Cancel property of the FormClosingEventArgs
argument to true
when you require the close-operation to be cancelled. And an explicit Environment.Exit(0)
is normally not required since the form is on its way to being closed any way (the cancellation of the shutdown process is opt-in, not opt-out).
Replace the last bit with:
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
e.Cancel = (result == DialogResult.No);
just take it simple
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (PreClosingConfirmation() == System.Windows.Forms.DialogResult.Yes)
{
Dispose(true);
Application.Exit();
}
else
{
e.Cancel = true;
}
}
private DialogResult PreClosingConfirmation()
{
DialogResult res = System.Windows.Forms.MessageBox.Show(" Do you want to quit? ", "Quit...", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
return res;
}
e.Cancel on the FormClosing event will stop the closing process
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (CloseCancel()==false)
{
e.Cancel = true;
};
}
public static bool CloseCancel()
{
const string message = "Are you sure that you would like to cancel the installer?";
const string caption = "Cancel Installer";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
return true;
else
return false;
}
The question is now old but this way is more simple and short, and I think it can be useful to those who arrive on this page:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (MessageBox.Show("Are you sure that you would like to cancel the installer?", "Cancel Installer", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
and use elsewhere this.Close()
rather than a function.
protected Boolean CanClose(Boolean CanIt)
{
if(MessageBox.Show("Wanna close?", "Cancel Installer", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ShowDialog() == DialogResult.Yes)
{
// Yes, they want to close.
CanIt = true;
}
else
{
// No, they don't want to close.
CanIt = false;
}
return CanIt;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if(CanClose(false) == true)
{
this.Dispose(true);
}
else
{
e.Cancel = true;
}
}
I'm unsure of how to handle the other scenario you mentioned (handling the 'X' click). Maybe you could do something like this (psuedo-code):
// IF CLICKED YES
THEN CLOSE
// ELSE-IF CLICKED NO
THEN DO NOTHING
// ELSE
THEN DO NOTHING