Reputation: 35
I seem to be having difficult in having a Dialog box pop up and function properly when a use clicks the red "X" button in the top right corner of the application. I can make the Dialog appear to ask if they really want to close the application, but regardless of what they click, it will close the form. The code I have is as follows;
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure want to close?", "Close Program", MessageBoxButtons.OKCancel);
if (dr == DialogResult.Cancel)
{
e.Cancel = false;
}
}
I have also tried instead of e.Cancel to check if dr is equal to ok but the same situation happens.
Any thoughts?
Upvotes: 2
Views: 58
Reputation: 56982
e.Cancel = true;
cancels the action. and it is by default false
. you are not setting it to true anywhere. try this.
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure want to close?", "Close Program", MessageBoxButtons.OKCancel);
if (dr == DialogResult.Cancel)
{
e.Cancel = true;
}
}
oneliner:
e.Cancel = MessageBox.Show("Are you sure want to close?", "Close Program", MessageBoxButtons.OKCancel) == DialogResult.Cancel;
Upvotes: 3
Reputation: 108
The Closing event occurs as the form is being closed. When a form is closed, all resources created within the object are released and the form is disposed. If you cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true.
e.Cancel = true;
Upvotes: 0
Reputation: 17428
The issue is that you are never setting e.Cancel
to true
. I would modify your message box to show Yes and No buttons as I feel it makes it clearer to the user and then I would just set e.Cancel
to true if the user chooses No.
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure want to close?", "Close Program", MessageBoxButtons.YesNo);
e.Cancel = dr == DialogResult.No;
}
Upvotes: 0