Reputation: 119
I wrote this code to handle the shutdown of the program/window when I press the Exit-Button:
private void MIExit_Click(object sender, RoutedEventArgs e)
{
var close = MessageBox.Show("Do you want to close the programm?", "", MessageBoxButton.YesNo);
if (close == MessageBoxResult.No)
return;
else
Application.Current.Shutdown();
}
The problem is I have to press "yes" twice for the application to close and I don`t understand why.
Thank you, Filippo
Upvotes: 0
Views: 99
Reputation: 119
ok sorry... I know why. I handled this for the "X" symbol top right on the window:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
var close = MessageBox.Show("Do you want to close the programm?", "", MessageBoxButton.YesNo);
if (close == MessageBoxResult.No)
e.Cancel = true;
else
e.Cancel = false;
}
and obviously the messageBox appears two times...
Upvotes: 1
Reputation: 17402
Are you possibly subscribing to the event twice? I would first handle the event so it doesn't bubble up, then add a simple flag so that your MessageBox
does not get called twice.
private bool _shuttingDown;
private void MIExit_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
if (_shuttingDown) return;
_shuttingDown = true;
var close = MessageBox.Show("Do you want to close the programm?", "", MessageBoxButton.YesNo);
if (close == MessageBoxResult.No)
{
_shuttingDown = false;
return;
}
Application.Current.Shutdown();
}
Upvotes: 0
Reputation: 41
There is no problem in your Code you posted.
Probably you have somewhere else a mistake.
I tried it like this:
Xaml:
<Button Click="MIExit_click">Exit</Button>
C#:
private void MIExit_click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("close?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Application.Current.Shutdown();
else return;
}
Works fine.
Upvotes: 0