26
votes

Stupidly simple question I can't figure out.

I have a WPF application, and I want to display a Logon dialog box first (before the main window shows up).

If the user logs on successfully, then I want to show the main window, if not, I want to exit the application.

How does one do this correctly?

3

3 Answers

46
votes

I think I figured out what I was trying to do.

1) I needed to set the "StartupUri" in the App.xaml to "Logon.xaml", where Logon.xaml is my logon window.

2) in the LogonButton_Click event handler, I added the following

if (blnAuthenticateSuccessful) {
    MainWindow main = new MainWindow();
    App.Current.MainWindow = main;
    this.Close();
    main.Show();
}

This seems to accomplish what I want.

4
votes

If you wanted a new window to appear to allow the user to enter their login information, then I have added some code below. However, creating a true Modal Dialog box is a bit more complicated in WPF so I haven't explained it here. There is information about modal dialog boxes in WPF here: http://msdn.microsoft.com/en-us/library/aa969773.aspx

From the MainWindow you can open the login window and hide the main window with this:

// Code for MainWindow

// Create a new instance of the login window and then show it
LoginWindow loginWindow = new LoginWindow();
loginWindow.Show();

// Hide the MainWindow until later
this.Hide();

Then use this on the login page to show the main window again once the user has logged in:

// Code for Login window

// This code finds the main window again and shows it
Application.Current.MainWindow.Show();
2
votes

I know its an old question but I had a similar problem and I solved it bit differently so just wanted to add that so in future someone might benefit from it.

To solve the problem you can change application shutdown mode to OnExplicitShutdown and then call Application.Shutdown(0) whenever you want to. For example:

public App()
{
    App.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // assume code below is for displaying dialog
    if (MessageBox.Show("Continue?", "", MessageBoxButton.YesNo) == MessageBoxResult.No)
        App.Current.Shutdown(0);
}

Here in the constructor, I'm changing application shudown mode and calling Shutdown method when I need to.

Caution: When you change ShutdownMode make sure to call Shutdown method otherwise your application will be in memory even after main window closes. I've overrided OnClosed method in my MainWindow to do that:

protected override void OnClosed(EventArgs e)
{
    base.OnClosed(e);
    App.Current.Shutdown(0);
}