Reputation: 1547
I am using the FormClosing event on a C# Windows Form to ask the user to confirm before exiting. I only wish to show this message if the user specifically closes the form using the red cross in the corner of the form window. When I close or hide a form manually I do not wish to show the confirm message (e.g. manually calling form.Close()).
Is it possible to check to see if the user has pressed the red cross?
Thanks.
Upvotes: 3
Views: 7943
Reputation: 8116
If you programatically call this.Close()
or have the user clicking the X, you get the CloseReason.UserClosing
for both so thats not a valid check.
See the below code for a "hacky" solution which basically invokes this.Close if OnClosing is passed a null
parameter.
private void button1_Click(object sender, EventArgs e)
{
OnClosing(null);
}
protected override void OnClosing(CancelEventArgs e)
{
if (e == null)
{
// Raise your Message or Cancel
this.Close();
}
else
{
base.OnClosing(e);
}
}
Upvotes: 2
Reputation: 15704
Out of the box, there isn't an easy way to detect this kind of behaviour. While there is a "FormClosingEventArgs.CloseReason" property that you can check on the FormClosing event, it won't really get specific about the reason it closes.
From MSDN, the description of the 'UserClosing' enum value is:
The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window's control menu, or pressing ALT+F4.
So as you can see there are a lot of reasons listed, but not one specifically.
I think that the best you are going to do is remove the window border (including the buttons) and place your own close button upon it, and catch its click event to get the behaviour that you want. I've seen it done before, and it does work, though it may not look as 'nice' as the normal window buttons.
Upvotes: 0
Reputation: 22779
use FormClosing
event handler and put this simple code:
if (MessageBox.Show(this, "Do you want to close the Application?", "Exit App", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
//close app code
}
Upvotes: 0
Reputation: 12259
You can check the CloseReason
property of the event args passed to the FormClosing
event.
Upvotes: 0