I'm building the WPF app with multiple forms, and my goal is that, on, let's say LoginForm I have a button called Login, which, when clicked, closes current form (LoginForm from above) and opens another form (let's say Form1).
Note that I'm trying to have only one form opened at a time.
Code -
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if(everything okay)
{
Form1 frm = new Form1();
frm.Show();
Close();
}
else
{
return;
}
}
This works fine. But, my second idea is that, if X in the top right corner is clicked, I want to close this form, and not to open any other, basically exiting the app.
Code-
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult rez = MessageBox.Show("Do you wish to leave the app?", "Question?", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (rez != MessageBoxResult.Yes)
{
e.Cancel = true;
}
}
This is where my problem starts, I've found that Window_Closing and this.Close() are same event, so, when I click the Login button, MessageBoxResult still shows up, even tho that is not my goal. I want to somehow separate those two events, if that is possible. How can I do so?
CodePudding user response:
You could temporarily unhook the event handler just before you call Close()
:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (everything okay)
{
Form1 frm = new Form1();
frm.Show();
Closing -= Window_Closing;
Close();
Closing = Window_Closing;
}
else
{
return;
}
}
Or use a bool
variable to determine whether to display the MessageBox
:
private bool _showMessageBox = true;
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (everything okay)
{
Form1 frm = new Form1();
frm.Show();
_showMessageBox = false;
Close();
_showMessageBox = true;
}
else
{
return;
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_showMessageBox)
return;
MessageBoxResult rez = MessageBox.Show("Do you wish to leave the app?", "Question?", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (rez != MessageBoxResult.Yes)
{
e.Cancel = true;
}
}
CodePudding user response:
this.Close is not a event. this.Close() is a method and after that the event Window_Closing is raised
Try something like that:
Form1 frm = new Form1();
Hide();
frm.ShowDialog();
Close();
you create a form, then you hide the login form and then you show the Dialog of the form. The Close will then be raised after the new Form1() is closed.