views:

3312

answers:

4

I am new to C# and .NET programming. I want to design an application that opens up with a small login screen and when user presses the "Login" button, my program should close the login form and pass to a new form. How can I achieve this simple process?

Thanks.

+8  A: 

This could be a solution;

In LoginForm;

public bool IsLoggedIn { get; private set;}
public void LoginButton_Click(object sender, EventArgs e)
{
  IsLoggedIn = DoLogin();
  if(IsLoggedIn)
  {
    this.Close()
  }
  else
  {
    DoSomethingElse();
  }
}

In program.cs

static void Main()
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  LoginForm loginForm = new LoginForm();
  Application.Run(loginForm);
  if (loginForm.IsLoggedIn)
  {
    Application.Run(new OtherForm());
  }
}
yapiskan
A: 

The challenge here is what form you pass to the Application.Run() method. If you start the application with an instance of the login form and then close that form I believe the application will exit. No doubt there are several ways to handle this...

One way is to pass an instance of your main form to the Application.Run method (this ties the message loop to that form instance and not the login form). In the OnLoad method of the main form you can use a modal dialog to perform the login. i.e.

//--Main form's OnLoad method
protected override void OnLoad(EventArgs ea)
{
    // Remember to call base implementation
    base.OnLoad(ea);

    using( frmLogin frm = new frmLogin() )
    {
     if( frm.ShowDialog() != DialogResult.OK )
     {
      //--login failed - exit the application
      Application.Exit();
     }
    }     
}
Why you have to exit from application if login failed? Is your browser or tab closed when cannot log in?
yapiskan
You can set the exit behaviour in the project settings, so you could have it close when all forms are closed.
FrozenFire
You don't have to exit. It's just an example of one approach.Project settings exit behavior... Cool. Never noticed.
+2  A: 

Depending on the overall architecture of your application, I often like to let the main form control launching the login screen.

    //Program.cs:
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }

    //MainForm.cs
    private void MainForm_Load(object sender, EventArgs e)
    {
        this.Hide();
        Login login = new Login();
        if (login.ShowDialog() == DialogResult.OK)
        {
            //make assignments from login
            currentUser = login.User;
        }
        else
        {
            //take needed action
            Application.Exit();
            return;
        }
    }
Timothy Carter
A: 

If you do use .ShowDialog(), don't forget to wrap it around an using block, or use .Dispose on the login form after you are done. Model dialogs must be manually disposed.

Echiban