In my program I show a login form before the main form, once the program detects a successful login I use this:
MainForm Main = new MainForm();
Main.Show();
You can use ApplicationContext.MainForm to specify current main form for the application:
static class Program
{
public static ApplicationContext Context { get; set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Context = new ApplicationContext(new LoginForm());
// pass Context instead of just new LoginForm()
Application.Run(Context);
}
}
then in in login handler:
private void login_Click(object sender, EventArgs e)
{
Program.Context.MainForm = new MainForm();
// close login form
this.Close();
// set up context to track main form instead of login
Program.Context.MainForm.Show();
}
You need to specify your MainForm
when you staring application and in the Load
event handler of this form ask for login. In this case you will have runned application and Login
for on the starting:
Program.cs
Application.Run(new MainForm());
MainForm.cs
private void Form1_Load(object sender, EventArgs e)
{
LoginForm loginForm = new LoginForm();
if (loginForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// check login here
}
}
P.S. Close
will close your application completelly if it's main form of your application.
How about this.Close()
instead?
Try something more like this:
this.Hide();
Main.ShowDialog();
this.Close();
You want to hide the login form before you show the dialog, then close the login form after the dialog has been closed.
Simply closing the Login dialog will ultimately end the application, so that's not a real solution, but you still want to hide the login.
Simply put, put things in the order you want them to go in, especially when dealing with message loops.
First, you hide the login form.
Next, you show the Main form dialog, but prevent the caller of "ShowDialog()" from continuing until the dialog is closed.
Last, once the dialog is closed, you close the login form, ending the application.
Change the main form to be MainForm
, and when the application launches, in your MainForm_Load
launch login form as a dialogbox, so they cannot access the main form.
Application.Exit(0);
SetVisibilityCore
and call it inside MainForm_Load
.