tags:

views:

730

answers:

5

Using Windows Forms I would like to have a small login screen the user authorizes himself/herself through (say its Form1), so the main application (say its Form2) would be opened after login. But I suppose when I use Application.Run(Form1), after closing it the whole application closes.

Isn't there any other way except using invisible Form2? Something like run Form2 on demand and close originally ran Form1? Hope it makes sense to you :)

+3  A: 

The ApplicationContext class is what you need. There's an Application.Run(ApplicationContext) overload you can call.

See here for an example: http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx

VVS
+3  A: 

Create an overload of System.Windows.Forms.ApplicationContext, create Form1 first and then Form2 in its constructor.

Use Application.Run overload that accepts ApplicationContext object.

elder_george
+1. There is also an article on CodeProject (http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx) showing how to create a splash screen before the main form using `ApplicationContext`, but also has a simple explanation of how the whole thing works.
Groo
A: 

Try this approach. From your program mainline create your main form class, from within this class have a "go" function that calls out to a login form. If this function returns true you can proceed with a call to Application.Run(form).

MainForm form = new MainForm();
form.Show();
if (form.go())
{
  Application.Run(form);
}
else
{
  form.Close();
}

class MainForm 
{
  public bool go()
  {
    LoginFrom lf = new LoginForm()
    if (lf.ShowDialog() != DialogResult.OK)
    {
      return false;
    }
  }
}

A little simplistic perhaps but it should get you going in the right direction.

Lou
+2  A: 

You can call your authentication form before starting up your main application form inside of Program.cs (default name), such as:

    static void Main()
    {
        Form1 f1 = new Form1();
        DialogResult dr = f1.ShowDialog();
        if (dr == DialogResult.OK)
        {
            Application.Run(new Form2());
        }
        else
        {
            Application.Exit();
        }
    }

Inside of Form1 if they properly authenticate then you just need to end with:

    this.DialogResult = DialogResult.OK;
    this.Close();

If the authentication fails, you can allow them to re-attempt authentication, give them a max number of attempts, etc. Then when you decide they have had too much just call

    Application.Exit();
ManiacZX