Roxy'Pro
Roxy'Pro

Reputation: 4444

Implementing Log in form in WPF C#

I'm trying to make Log in window in my application, I'm pretty new to WPF and it's not going so well for me.

This is what I did, and I'm not even sure is this correct way, but anyway my question is described in code comments.

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Window_LogInScreen loginScreen = new Window_LogInScreen();
        loginScreen.ShowDialog();

        if (loginScreen.DialogResult == true)
        {
            MessageBox.Show("login success I should keep executing my application.."); // how could I continue my application if this condition is allright?
        }
        else
        {
            MessageBox.Show("login failed"); //how could I stop my application if I reach this code, and how to stay on LogIn_Screen form so user can enter password again..
        }

        lblDate.Text = DateTime.Now.Date.ToString("MM/dd/yyyy");
        lblTime.Text = DateTime.Now.ToString("HH:mm:ss");
    }


}

My Window_LogInScreen :

public partial class Window_LogInScreen : Window
{
    public Window_LogInScreen()
    {
        InitializeComponent();
        lblPasswordBox.Focus();
    }


    private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            if (lblPasswordBox.Password == "1")//lets say pw is "1" for testing purposes
            {
                this.DialogResult = true;
                this.Close();
            }
            else
                this.DialogResult = false;
        }
    }
}

So guys how could I achieve that?

In window forms I would do this is Program.cs, but in WPF I'm somehow lost and I don't know how to achieve this on a right way,

but my logic is:

1) open LogIn screen before application run, check for password when user press Enter on keyboard, if password is OK then set DialogResult to true,

2) go back to MainWindow, check there is DialogResult==true, if yes, then keep going with execution of MainWindow, else, stop application and stay on LogIn_Screen so user can enter password again..

Thanks guys, Cheers

EDIT after Xioy312 answer:

@Xiaoy312 The code you posted is really awesome, and I'm really intrested in this code, but it looks a bit incomprehensible to me..

Let's back to your first EDIT,

  if (e.Key == Key.Enter && lblPasswordBox.Password == "1")
    {
        this.DialogResult = true;
        this.Close();
    }

how come this.DialogResult will not become false if condition is not satisfied? because with that code that you have posted in your answer before last edit, MessageBox.Show("login failed"); from Application_Startup would never be reached, and I'm wondering why? I guess if mentioned condtion (if (e.Key == Key.Enter && lblPasswordBox.Password == "1")) is not satisfied, than DialogResult will be false and MessageBox.Show("login failed"); from else part would be called? but actualy that is not true, because here we have that failed attempt is silent, and I'm wondering why?

And also, how come application would exit with this Behavior? Can you explain little bit what's happening behind, as much as I can se you'r assigning value to a DialogResult in case it is "1".. ?

#region Behavior 1: Exit the application on invalid password
        this.DialogResult = lblPasswordBox.Password == "1";
        this.Close();
        #endregion

Could you explain this code little bit, I would be so thankful!

Upvotes: 0

Views: 12812

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

If you want to lock the users out of the application unless they are authenticated, you can define a startup routine instead of opening the MainWindow directly.

In App.xaml, remove the StartupUri property and add these two instead:

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup"
             ShutdownMode="OnExplicitShutdown">
</Application>

OnExplicitShutdown is there to prevent the application from shutting down after we are done with the login window.

In App.xaml.cs, you should find the event handler Application_Startup where you can dictate the flow of the application:

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
        if (new LoginWindow().ShowDialog() == true)
        {
            MessageBox.Show("login success I should keep executing my application..");
            new MainWindow().ShowDialog();
        }
        else
        {
            MessageBox.Show("login failed");
        }
    }
    finally
    {
        Shutdown();
    }
}

EDIT: The login logic should be contained within the LoginWindow, and should not be leaked into the Application or MainWindow:

private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    // lets say pw is "1" for testing purposes
    if (e.Key == Key.Enter && lblPasswordBox.Password == "1")
    {
        this.DialogResult = true;
        this.Close();
    }
}

EDIT: If you don't like the invalid password to fail silently, you can change this behavior in PreviewKeyDown:

private void LoginWindow_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // You should keep only one of two:
        #region Behavior 1: Exit the application on invalid password
        this.DialogResult = lblPasswordBox.Password == "1";
        this.Close();
        #endregion
        #region Behavior 2: Warn the user on invalid password
        if (lblPasswordBox.Password == "1")
        {
            this.DialogResult = true;
            this.Close();
        }
        else
        {
            MessageBox.Show("invalid password");
        }
        #endregion
    }
}

Upvotes: 5

Related Questions